|
dev
newsgroups
|
|||||||||||||||||||||||
|
|||||||||||||||||||||||
Help needed: Custom data-bound control modifies Rows just by navigating through DataTableTextBox. Its code is basically class MyBox: TextBox { public string MyText { get { return base.Text; } set { base.Text = value; } } } and the only difference between MyBox and TextBox is that MyBox has a blue background :) I put MyBox on a form which also holds a DataSet and a BindingSource. Then I bind MyBox.MyText to a field in a DataTable. When I use it on one record, it works fine (MyBox shows value in the field and by typing in it I can modify the value). But when I try navigating through the DataTable using the BindingSource.MovePrevious and .MoveNext methods, DataRows get modified even if I don't change anything (by typing in MyBox). I then replace MyBox with TextBox, bind it the same way and navigation doesn't modify rows, which is expected behavior. What is different between the original TextBox and MyBox? Why does MyBox modify rows? I detect modified rows by calling GetChanges and checking the Rows.Count property, and every time I navigate to another row, it gets modified. I suppose I should implement something to support data change notifications in MyBox class, but I don't know what. Please help! OK, I found the solution to this in MSDN. The article is called
Windows Forms Programming How to: Add Change Notification for Data Binding Unfortunately, the code in MSDN article doesn't work because they forgot (?) an "event" keyword which is crucial in this case. My MSDN Library is from 2005, but on the online MSDN library (http://msdn2.microsoft.com/en-us/library/ms229615.aspx) they have the same old sample without the "event" keyword. Do they check their samples at all? I lost two days trying to figure this out. The correct code follows: class MyBox: TextBox { public MyBox(): base() { // when users type something in the base TextBox, MyBox has to update itself base.TextChanged += new EventHandler(MyBox_TextChanged); } void MyBox_TextChanged(object sender, EventArgs e) { this.MyText = base.Text; } // This event MUST BE declared. Note the "event" keyword! public event EventHandler MyTextChanged; private void OnMyTextChanged() { if (MyTextChanged != null) { MyTextChanged(this, new EventArgs()); } } // And this is the bindable property "MyText" [Bindable(BindableSupport.Yes, BindingDirection.TwoWay)] public string MyText { get { return base.Text; } set { base.Text = value; OnMyTextChanged(); } } } |
|||||||||||||||||||||||