TextBox数据绑定DataView出错,导致集合中的两个绑定绑定到同一个属性
public partial class Form1 : Form{
private DataView dv = new DataView();
private BindingManagerBase bm;
public Form1()
{
InitializeComponent();
departmentNameTextBox1.ReadOnly = true;
this.Load += new EventHandler(Form1_Load);
}
void Form1_Load(object sender, EventArgs e)
{
string sqlConnectString = @"Data Source=.\SQLEXPRESS;
Integrated security=SSPI;Initial Catalog=AdventureWorks;";
string sqlSelect = "SELECT * FROM HumanResources.Department";
//使用Department表数据填充DataTable
SqlDataAdapter da = new SqlDataAdapter(sqlSelect, sqlConnectString);
DataTable dt = new DataTable();
da.Fill(dt);
// 基于表创建DataView,设置排序规则
dv = dt.DefaultView;
dv.Sort = "DepartmentID";
// 创建数据绑定上下文
bm = BindingContext[dv];
// 为文本框2添加绑定
departmentNameTextBox2.DataBindings.Add("Text", dv, "Name"); //编译时报错“这将导致集合中的两个绑定绑定到同一个属性”
//完全按书上的例子写的,不知道哪里错了,自带源码运行无误,但自己写的一样的代码就是出错?
//怎么会出现两个绑定绑定到同一个属性呢,这不只有一个绑定吗???????????????????????????
// 初始化文本框
departmentIDTextBox.Text = "1";
GetDepartmentName(1);
}
private void GetDepartmentName(int departmentID)
{
// 在DataView中基于指定部门ID查找数据行
int rowIndex = dv.Find(departmentID);
if (rowIndex == -1)
{
MessageBox.Show("非法DepartmentID", "错误",
MessageBoxButtons.OK, MessageBoxIcon.Error);
}
else
{
departmentNameTextBox1.Text = (string)dv[rowIndex]["Name"];
bm.Position = rowIndex;
}
}
private void getNameButton_Click(object sender, EventArgs e)
{
int departmentID;
// 提取信息
if (int.TryParse(departmentIDTextBox.Text, out departmentID))
{
GetDepartmentName(departmentID);
}
else
{
MessageBox.Show("非法 DepartmentID", "错误",
MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}