【发布时间】:2011-10-21 15:54:15
【问题描述】:
我在将我的用户控件数据绑定到 DGV 时遇到问题。当我只绑定到我的控件的 1 个文本框时,它可以工作。但是,当我绑定多个文本框时,只有第一个有效。请帮忙。我是 C# 初学者。下面是代码。
- 我创建了 Window Form 应用程序(名为 Test100)
- 我在项目 Test100 中添加了一个用户控件“MyBox”,我在其中添加了 2 个文本框(textBox1 和 textBox2)
-
在 MyBox.cs 中,我有以下内容:
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(); } } -
构建后,我打开了我的 Form 1 并:在我的 Form1 中添加了 MyBox 控件,在 Form 1 中添加了一个 DGV,添加了一个用于刷新 Form 的按钮。数据列表直接在 Form1.cs 中生成。 Form1.cs 如下:
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; } } 开始调试后,我更改了Box1的值并按下了button1,DGV上的TrackID随着我更改的值而变化。但是,当我更改Box2的值并按下button1时,DGV上的Name列没有改变,但Box2恢复了原来的值。
- 如果我只绑定 Box2,那么 Box2 就可以了。
请帮忙。谢谢。
【问题讨论】:
-
您的代码解决了我的问题!谢谢