首页 > 解决方案 > 将列表框项目转换为 datagridview 复选框列中的选中行

问题描述

我想使数据网格(复选框列)行打勾。数据网格中与列表框项目中的学生代码列匹配的那些行。

我已经尝试了下面的代码。但我没有得到正确的结果

private void btnConvertItemsToCheckedRows_Click(object sender, EventArgs e)
{
  if(  ListBox1.ListBox.Items.Count>0)
  {
    for (int i = 0; i <ListBox1.ListBox.Items.Count; i++)
    {
      foreach (DataGridViewRow row in GridStudents.DataGridView.Rows)
      {
        if(row.Cells["StudentCode"].Value.ToString().Equals(ListBox1.ListBox.Items[i]))
        {
          GridStudents.DataGridView.Rows[i].DataGridView["ChekboxColumn", i].Value = true;
        }
      }
    }

  }
}

标签: c#listbox

解决方案


试试这个:

private void btnConvertItemsToCheckedRows_Click(object sender, EventArgs e)
{
  if(  ListBox1.ListBox.Items.Count>0)
  {
    for (int i = 0; i <ListBox1.ListBox.Items.Count; i++)
    {
      foreach (DataGridViewRow row in GridStudents.DataGridView.Rows)
      {
        if(row.Cells["StudentCode"].Value.ToString().Equals(ListBox1.ListBox.Items[i]))
        {
          DataGridViewCheckBoxCell chk = (DataGridViewCheckBoxCell)row.Cells["ChekboxColumn"];
           chk.TrueValue = true;
           chk.Value = chk.TrueValue;
        }
      }
    }
    GridStudents.EndEdit();
  }
}

推荐阅读