I have a problem with data binding my user control into a DGV. When I bind into only 1 textbox of my control, it works. However when I bind more than 1 textbox, only the first works. Please help. I am a C# beginner. Below is the code.
- I created Window Form app (named Test100)
- I added a user control “MyBox” into the project Test100, I added 2 textboxes into it (textBox1 and textBox2)
-
In the MyBox.cs, I have the following:
using System; using System.Collections.Generic; using System.ComponentModel; using System.Drawing; using System.Data; using System.Linq; using System.Text; using System.Windows.Forms; namespace Test100 public partial class MyBox : UserControl { public string Box1 { get { return textBox1.Text; } set { textBox1.Text = value; } } public string Box2 { get { return textBox2.Text; } set { textBox2.Text = value; } } public MyBox() { InitializeComponent(); } } -
After building, I opened my Form 1 and: added the MyBox control into my Form1, added a DGV into Form 1, added a button for refreshing the Form. The data list is produced directly in the Form1.cs. The Form1.cs is listed below:
public partial class Form1 : Form { private List<Track> trackList = new List<Track>(); public Form1() { InitializeComponent(); } private void Form1_Load(object sender, EventArgs e) { trackList.Add(new Track { TrackID = 1234, Name = "Name1111" }); trackList.Add(new Track { TrackID = 5678, Name = "Name2222" }); trackList.Add(new Track { TrackID = 9012, Name = "Name333" }); BindingSource bindingSource1 = new BindingSource(); bindingSource1.DataSource = trackList; dataGridView1.DataSource = bindingSource1; myBox1.DataBindings.Add("Box1", dataGridView1.DataSource, "TrackID"); myBox1.DataBindings.Add("Box2", dataGridView1.DataSource, "Name"); } private void button1_Click(object sender, EventArgs e) { this.Refresh(); } } public class Track { public int TrackID { get; set; } public string Name { get; set; } } -
After start debugging, I changed the Box1 value and pushed the button1, the TrackID on the DGV changed with the value I changed. However, when I changed the value of Box2 and pushed the button1, the Name column on DGV did not change but the Box2 returned to the original value.
- If I bind only the Box2, then Box2 will work.
Please help. Thanks.
Okay. Never mind. I found that this is a known issue that MS recognized from 2004 and fixed in .Net 1.1.
http://support.microsoft.com/kb/812918
However I am using VS 2010 and doing Winform, I tried to apply the fix that MS fixed for this issue and it works. Thank you for reading.