0

我想获取选中复选框的行的值。我是 C# windows 窗体的新手,到目前为止还没有成功。我想最终使用这些行值,所以如果用户选择多行,那么我应该为那些选中的行获得值。另外,我已将选择模式设置为“fullrowselect”

请建议更改我的代码

private void button1_Click(object sender, EventArgs e)
{
    StringBuilder ln = new StringBuilder();
    dataGridView1.ClearSelection();
    foreach (DataGridViewRow row in dataGridView1.Rows)
    {
        if (dataGridView1.SelectedRows.Count>0 )
        {                    
            ln.Append(row.Cells[1].Value.ToString());
        }
        else
        {
            MessageBox.Show("No row is selected!");
            break;                    
        }
    }
    MessageBox.Show("Row Content -" + ln);
}
4

3 回答 3

0

SelectedRows 是选择的行数(或突出显示的行数),而不是检查的行数。代码中的第二个问题是您正在执行 foreach 行,但在内部您使用的是 dataGridView,而不是当前行。这就是你的 if 必须是这样的:

private void button1_Click(object sender, EventArgs e)
{
    const int checkBoxPosition = 3; //You must type here the position of checkbox.
                                    // Remember, it's zero based.

    StringBuilder ln = new StringBuilder();
    dataGridView1.ClearSelection();
    foreach (DataGridViewRow row in dataGridView1.Rows)
    {
      if (row.Cells[checkBoxPosition].Value == true)
        {                    
            ln.Append(row.Cells[1].Value.ToString());
        }
        else
        {
            MessageBox.Show("No row is selected!");
            break;                    
        }

    }
    MessageBox.Show("Row Content -" + ln);
}
于 2015-05-18T15:04:28.467 回答
0

在你的网格中有一个复选框列不会改变任何行的内部状态,所以你需要自己遍历它们来评估。这应该可以解决问题,尽管您需要为 checkBoxColumnIndex 中的复选框列提供正确的列索引

int checkBoxColumnIndex = nnn; // 0 based index of checkboxcolumn
private void button1_Click(object sender, EventArgs e)
{
    List<string> checkedItems = new List<string>();

    dataGridView1.ClearSelection();
    foreach (DataGridViewRow row in dataGridView1.Rows)
    {
        DataGridViewCheckBoxCell checkBox= row.Cells[checkBoxColumnIndex] as DataGridViewCheckBoxCell;

        if (Convert.ToBoolean(checkBox.Value) == true)
        {                    
             checkedItems.Add(row.Cells[1].Value.ToString());
        }
    }
    if (checkItems.Count > 0)
        MessageBox.Show("Row Content -\r\n" + String.Join("\r\n", checkedItems));
    else
        MessageBox.Show("No row is selected!");
}

诚然,List<string>如果您只想打印列表,这是一个沉重的结构,但如果您需要对所有检查的值进行进一步处理,它会很有用。

于 2015-05-18T16:15:35.537 回答
0

这是您的代码版本,可能是您想要的......但很难说,因为您正在谈论选定的行但在处理行之前清除选择!

这没有任何意义..也许你的意思是选中的行?好的,你做到了,所以你去:

  private void button1_Click(object sender, EventArgs e)
  {
      StringBuilder ln = new StringBuilder();
      dataGridView1.ClearSelection();
      foreach (DataGridViewRow row in dataGridView1.Rows)
      {
          if (((bool?)row.Cells[0].Value) == true)
          {
               ln.Append(row.Cells[1].FormattedValue);
          }
      }
      if (ln.Length <= 0) MessageBox.Show("No rows are checked!");
      else MessageBox.Show("Rows content: " + ln);
 }
于 2015-05-18T17:15:51.740 回答