datatable绑定comboBox显示数据[C#]


实现方法:

    1、生成datatable,并为combox绑定数据源:

           comboBox1.DataSource = dt1;
 
          comboBox1.DisplayMember = "用户编码";
 
          comboBox1.ValueMember = "ID";
 
          this.comboBox1.SelectedIndex = -1;

   2、在combox的SelectedIndexChanged事件中添加如下方法:

       private void comboBox1_SelectedIndexChanged(object sender,EventArgs e)
 
      {
 
          int iCurrentIndex = this.comboBox1.SelectedIndex;
 
          if (iCurrentIndex < 0) return;

           DataRow dr = dt1.Rows[iCurrentIndex];
 
          iID = Int32.Parse(dr["ID"].ToString());

       }

另:如果textBox也想绑定该数据源,实现连动(如输入编码显示对应名称)

   3、在textBox的TextChanged事件中添加如下方法:

       private void textBox1_TextChanged(object sender, EventArgs e)
 
      {
 
          string strUserNo = this.textBox1.Text.Trim();
 
          for (int i = 0; i < dt1.Rows.Count; i++)
 
          {
 
              if (dt1.Rows[i]["用户编码"].ToString() == strUserNo)
 
              {
 
                  this.comboBox1.SelectedIndex = i;
 
                  break;
 
              }
 
              else
 
              {
 
                  this.comboBox1.SelectedIndex = -1;
 
              }
 
          }
 
      }

你可能感兴趣的:(c#.net)