1
我使用DataBindings從我的客戶對象到組合框。我試圖實現的行爲是標籤文本將反映選擇的名稱。爲什麼我的標籤沒有通過組合框更新
using System;
using System.Collections.Generic;
using System.Windows.Forms;
namespace WindowsFormsApplication1
{
public partial class Form1 : Form
{
Customer selectedCustomer;
List<Customer> list = new List<Customer>();
public Form1()
{
InitializeComponent();
selectedCustomer = new Customer() { Id = 2, FirstName = "Jane" };
}
private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
label1.Text = selectedCustomer.FirstName;
}
private void Form1_Load(object sender, EventArgs e)
{
list.Add(new Customer() { Id = 1, FirstName = "John" });
list.Add(new Customer() { Id = 2, FirstName = "Jane" });
comboBox1.DisplayMember = "FirstName";
comboBox1.ValueMember = "Id";
comboBox1.DataSource = list;
comboBox1.DataBindings.Add("Text", selectedCustomer, "FirstName");
}
}
public class Customer
{
public int Id { get; set; }
public string FirstName { get; set; }
}
}
但不是DataBindings應該自動更新源(在這種情況下是selectedCustomer對象)? – Rod
@Rod問題是當選擇改變時你沒有更新'selectedCustomer'字段 –
你可以爲標籤添加綁定label1.DataBindings.Add(「Text」,selectedCustomer,「FirstName」); –