2015年1月20日 星期二

[學習] 當二個以上Combobox繫結相同來源時,若其中一個改變選項,則其它相同參考的Combobox不隨之改變....

程式:[用不同的BindingContext就好了]
        If MyUserProgInfo.frmLogin使用WebServices Then
            cbo_單據別1.DataSource = ws.ItemtblB備案手冊單據別基本資料表_GetMdl()
        Else
            cbo_單據別1.DataSource = New BLLMSSQL.BllBasicCtrlsSource().ItemtblB備案手冊單據別基本資料表
        End If
        cbo_單據別1.DisplayMember = "DisplayValue"
        cbo_單據別1.ValueMember = "單據別"

        cbo_單據別2.BindingContext = New BindingContext()
        cbo_單據別2.DataSource = cbo_單據別1.DataSource
        cbo_單據別2.DisplayMember = "DisplayValue"
        cbo_單據別2.ValueMember = "單據別"

參考:
WinForms ComboBox data binding gotcha
Multiple Combo Boxes With The Same Data Source (C#)

BindingContext 類別
关于控件使用DataBindings.Add方法进行简单绑定的问题

Bind multiple ComboBox to a single List - Issue: When I select an item, all combo boxes change

WinForm数据绑定--BindingContext
How can i bind data to a datagridview combobox column?

You could create a BindingList<> object to hold your objects and then bind that list to the three controls. Then setting the BindingContexts to different objects would let the 3 controls have different positions with a single list.
  
public partial class Form1 : Form
  {
  public Form1()
  {
    InitializeComponent();
  }
 
  private void Form1_Load(object sender, EventArgs e)
  {
    BindingList<MyObject> list = new BindingList<MyObject>();
    list.Add(new MyObject("Ramya", 43));
    list.Add(new MyObject("Manju", 43));
    list.Add(new MyObject("Gulnus", 43));
    list.Add(new MyObject("Sona", 43));
 
    dataGridView1.DataSource = list;
    comboBox1.DataSource = list;
    comboBox1.DisplayMember = "Name";
    comboBox1.ValueMember = "Name";
 
    comboBox2.DataSource = list;
    comboBox2.DisplayMember = "Name";
    comboBox2.ValueMember = "Name";
 
    comboBox1.BindingContext = new BindingContext();
    comboBox2.BindingContext = new BindingContext();
    dataGridView1.BindingContext = new BindingContext();
 
  }
  }
 
  public class MyObject
  {
  private string mName;
  private int mAge;
 
  public MyObject(string s, int i)
  {
    mName = s;
    mAge = i;
  }
  public string Name
  {
    get { return mName; }
    set { mName = value; }
  }
  public int Age
  {
    get { return mAge; }
    set { mAge = value; }
  }
  public override string ToString()
  {
    return Name;
  }
  }

沒有留言:

張貼留言