在C# WinForm中,可以通過數(shù)據(jù)綁定實現(xiàn)將數(shù)據(jù)源和控件進(jìn)行關(guān)聯(lián),實現(xiàn)數(shù)據(jù)的顯示和更新。下面是一個簡單的例子來演示如何實現(xiàn)數(shù)據(jù)的綁定和更新:
首先,在WinForm窗體上添加一個DataGridView控件和兩個TextBox控件,用于顯示和編輯數(shù)據(jù)。
創(chuàng)建一個數(shù)據(jù)模型類,例如:
public class Person
{
public int Id { get; set; }
public string Name { get; set; }
public int Age { get; set; }
}
public partial class MainForm : Form
{
private BindingList<Person> persons;
public MainForm()
{
InitializeComponent();
persons = new BindingList<Person>();
dataGridView1.DataSource = persons;
textBox1.DataBindings.Add("Text", persons, "Id");
textBox2.DataBindings.Add("Text", persons, "Name");
textBox3.DataBindings.Add("Text", persons, "Age");
}
private void button1_Click(object sender, EventArgs e)
{
persons.Add(new Person { Id = 1, Name = "Alice", Age = 25 });
persons.Add(new Person { Id = 2, Name = "Bob", Age = 30 });
}
private void button2_Click(object sender, EventArgs e)
{
int index = dataGridView1.CurrentCell.RowIndex;
persons[index].Id = int.Parse(textBox1.Text);
persons[index].Name = textBox2.Text;
persons[index].Age = int.Parse(textBox3.Text);
}
}
在上面的代碼中,我們創(chuàng)建了一個BindingList
通過以上步驟,就可以實現(xiàn)在C# WinForm中進(jìn)行數(shù)據(jù)的綁定和更新操作。