CheckedListBox使用之获取选中值

1.使用CheckedListBox1.Items.Add循环方式
 
  赋值:
  foreach (DataRow dr in ds.Tables[0].Rows)
  {
     checkedListBox1.Items.Add(dr["Name"]);
  }
 
  选中索引:
  foreach (int indexChecked in checkedListBox1.CheckedIndices)
  {
      MessageBox.Show("Index#: " + indexChecked.ToString());             
  }

  选中值:
  foreach (object itemChecked in chk.CheckedItems)
  {
     MessageBox.Show("Item with title: " + itemChecked.ToString());
  }

2.使用DataSource方式

  赋值:
  CheckedListBox.DataSource = ds.Tables[0];
  CheckedListBox.DisplayMember = "Id";
  CheckedListBox.ValueMember = "Name";

  选中值:
  for (int count = 0; count < CheckedListBox1.CheckedItems.Count; count++)
  {
      string id = (CheckedListBox1.Items[CheckedListBox1.CheckedIndices[count]] as DataRowView)["Id"].ToString(); //获取ID
      string name = (CheckedListBox1.Items[CheckedListBox1.CheckedIndices[count]] as DataRowView)["Name"].ToString(); //获取名称
      MessageBox.Show("Id:" + id + " Name:" + name);
  }

你可能感兴趣的:(checked)