日期:2014-05-18  浏览次数:20995 次

C# combobox 联动 怎么绑定 valueMember 和 displayMember
怎么在combobox联动中设置ValueMember 和 DisplayMember?代码如下 。标红的地方怎么解决 ?
谢谢了
  public class ElmList
  {
  public string ElmStr;
 
  public int ElmId;
   
  public ElmList( int GetElmId,string GetElmStr)
  {
  this.ElmId = GetElmId;
  this.ElmStr = GetElmStr;
  }

  }


  private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
  {
  ArrayList ElLst=new ArrayList();
  ElLst.Clear();
  string connectStr = "Provider=Microsoft.Jet.OLEDB.4.0; Data Source=public.mdb";
  string citySqlStr = "select cityid , city from city where provinceid=" +Convert.ToInt32(comboBox1.SelectedValue);
  using(OleDbConnection odbConn=new OleDbConnection(connectStr))
  {
  OleDbCommand odbComm=new OleDbCommand(citySqlStr,odbConn);
  odbComm.CommandTimeout=60;
  odbConn.Open();
  OleDbDataReader odbReader=odbComm.ExecuteReader();
  ElLst.Add(new ElmList(0,"请选择市"));
  while(odbReader.Read())
  {
  ElLst.Add(new ElmList(odbReader.GetInt32(0),odbReader.GetString(1)));
  }
  odbReader.Close();
  }

  comboBox2.Items.Clear();

  foreach(ElmList list in ElLst)
  {
  comboBox2.Items.Add(list);这里竟然是 form1+ElmList
  comboBox2.ValueMember = Convert.ToString(list.ElmId);
comboBox2.DisplayMember = list.ElmStr;
  //我该怎么解决?
  }
  comboBox2.SelectedItem = comboBox2.Items[0];
  }


------解决方案--------------------
还是用数据源绑定方式吧,前两天回另一帖时写了一个例子,大概过程是这样的,你自己既然写过,那也应该明白怎么做

C# code
private void RegisterForm_Load(object sender, EventArgs e)
{
    SqlConnection con = new SqlConnection("server=root_db;database=users;uid=sa;password=");
    SqlDataAdapter da = new SqlDataAdapter("select group_id, group_name from mygroup", con);
    DataSet ds = new DataSet();
    da.Fill(ds, "group");
    DataTable dtGroup = ds.Tables["group"];

    comboBox1.DataSource = dtGroup;
    comboBox1.DisplayMember = "group_name";
    comboBox1.ValueMember = "group_id";
}

private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
    if (comboBox1.SelectedIndex > -1)
    {
        //注意以下两行代码,估计人的错误就在这里
        DataRowView drv = (DataRowView)comboBox1.SelectedItem;
        string gId = drv.Row["group_id"].ToString();
        SqlConnection con = new SqlConnection("server=root_db;database=users;uid=sa;password=");
        SqlDataAdapter da = new SqlDataAdapter("select user_id, user_name from myuser where group_id='" + gId + "'", con);
        DataSet ds = new DataSet();
        da.Fill(ds, "user");
        DataTable dtUser = ds.Tables["user"];

        comboBox2.DataSource = dtUser;
        comboBox2.DisplayMember = "user_name";
        comboBox2.ValueMember = "user_id";
    }
}