我有一个包含多个文本框和数据表的表单,数据表绑定到文本框,我正在处理数据表的RowChanged事件。
但是,只有在加载表单时(有两个以上的文本框)才会调用RowChanged事件两次,来自数据表的数据可以很好地加载到文本框中,但是当我更改文本框中的文本时文本框没有触发事件。然而,直接从数据表显示数据显示数据已更新。
代码:
private Clients.DataSetClients.ClientsDataTable dtClients = new DataSetClients.ClientsDataTable();
private Clients.DataSetClientsTableAdapters.ClientsTableAdapter taClients = new DataSetClientsTableAdapters.ClientsTableAdapter();
private void ClientsEdit_Load(object sender, EventArgs e)
{
dtClients.RowChanged += new DataRowChangeEventHandler(dtClients_RowChanged);
taClients.FillByID(dtClients, ClientID);
textForename.DataBindings.Add("Text", dtClients, "Forename", true, DataSourceUpdateMode.OnPropertyChanged);
//.......
// etc
//.......
textEmail.DataBindings.Add("Text", dtClients, "Email", true, DataSourceUpdateMode.OnPropertyChanged);
}
void dtClients_RowChanged(object sender, DataRowChangeEventArgs e)
{
MessageBox.Show("dtClients_RowChanged");
}
private void simpleButton1_Click(object sender, EventArgs e)
{
MessageBox.Show(dtClients.Rows[0]["Email"].ToString());
}
答案 0 :(得分:1)
您可以尝试连接绑定的BindingComplete
事件而不是DataTable上的RowChanged事件(更多用于添加行和行位置更改等)。
private void ClientsEdit_Load(object sender, EventArgs e)
{
// loading stuff
Binding ForenameBinding = new Binding("Text", dtClients, "Forename", true, DataSourceUpdateMode.OnPropertyChanged);
ForenameBinding.BindingComplete += Table_BindingComplete;
textForename.DataBindings.Add(ForenameBinding);
// loading stuff
}
void Table_BindingComplete(object sender, BindingCompleteEventArgs e) {
if (e.BindingCompleteContext == BindingCompleteContext.DataSourceUpdate)
MessageBox.Show("Source Updated!");
}
每次用户更改TextBox中的文本时,都会弹出MessageBox,因此它会在每个键击中触发。为避免这种情况,请将绑定模式更改为OnValidation
:
Binding ForenameBinding = new Binding("Text", dtClients, "Forename", true, DataSourceUpdateMode.OnValidation);
答案 1 :(得分:0)
private void button1_Click(object sender, EventArgs e)
{
List<string> names=new List<string>(){"Forename","Email","Phone"};
foreach (var name in names)
{
var txt = this.Controls["text" + name] as TextBox;
txt.DataBindings.Add("Text", dtClients, name, true, DataSourceUpdateMode.OnPropertyChanged);
}
}