是否可以仅在datagridview中的某些行添加CheckBoxcolumn

时间:2011-10-24 15:28:20

标签: winforms datagridview

我的数据网格视图如下

 RecordTypeCode   Content
   FileHeader      1111111111111
   BatchHeader     5666666666666
   EntryDetail     656546545644545
   BatchControl    8654654564564
   FileControl     945645

我想只在BatchHeader上设置复选框,并且可以使用EntryDetail。这是我将数据绑定到数据网格视图的方式

 if (line.StartsWith("1"))
{
  dcID = new DataColumn("RecordTypeCode");
  dt.Columns.Add(dcID);
  DataColumn dcSomeText = new DataColumn("Content");
  dt.Columns.Add(dcSomeText);
  dr = dt.NewRow();
  dr["RecordTypeCode"] = filecontrolvariables.rectype[line.Substring(0, 1)].ToString();
  dr["Content"] = line;
  dt.Rows.Add(dr);
}

if (line.StartsWith("5"))
{
   dr = dt.NewRow();
   dr = dt.NewRow();
  dr["RecordTypeCode"] = filecontrolvariables.rectype[line.Substring(0, 1)].ToString();
  dr["Content"] = line;
 dt.Rows.Add(dr);
}          

我想根据需要添加复选框,任何人都可以帮助我

我试过这个

if (e.RowIndex >= 0 && e.ColumnIndex >= 0)
{
  if (dataGridView2.Rows[e.RowIndex].Cells["RecordTypeCode"].Value.ToString() == "BatchHeader")
 {
    e.PaintBackground(e.ClipBounds, true);
     e.Handled = true;
  }
 }

我的数据绑定时的示例图片

enter image description here

我试过这个

 int columnIndex = -1;
 int rowIndex = -1;
 if (dataGridView2.CurrentCell != null)
 {
     columnIndex = dataGridView2.CurrentCell.ColumnIndex;
     rowIndex = dataGridView2.CurrentCell.RowIndex;
  }
   if (columnIndex == 0)
   {
     if (e.RowIndex >= 0)
    {
    if (dataGridView2.Rows[e.RowIndex].Cells["RecordTypeCode"].Value.ToString() == "Batch Header")
    {
      e.PaintBackground(e.ClipBounds, true);
      e.Handled = true;
     }
     }
   }

但是当我只检查BatchHeader

时,我的相应行显示为空

1 个答案:

答案 0 :(得分:2)

您需要使用cellpainting事件才能完全显示复选框。我不确定在数据绑定期间是否会有其他后果,但它没有显示我想要的行的复选框。

我已根据您的需要更新了该方法。

 private void dataGridView1_CellPainting(object sender, DataGridViewCellPaintingEventArgs e)
        {
            if (e.RowIndex >= 0 && e.ColumnIndex >= 0)
            {
                //if (e.ColumnIndex == <index of your checkbox column> && (e.RowIndex == 1 || e.RowIndex == 2))
                if (dataGridView2.Rows[e.RowIndex].Cells["RecordTypeCode"].Value.ToString() == "Batch Header" && e.ColumnIndex == <index of your checkbox column should be 0 sicne its the first column>)
                {
                    e.PaintBackground(e.ClipBounds, true);
                    e.Handled = true;
                }
            }
        }

e.RowIndex == 1 || e.RowIndex == 2的条件是基于batchheader和entrydetail不会改变其位置的事实。但如果这是动态的,那么您只需检查recordtype列中的文本以匹配BatchHeader和EntryDetail。

if语句是最重要的,它会检查哪个特定单元格(行,列)是您不想要的任何复选框。它们必须与AND(&amp;&amp;)一起使用,因为您需要一个特定单元格。如果您所解释的是您所需要的,您可以使用我编写的代码。您可能需要在if语句中再添加一个条目以获取条目详细信息,这需要使用OR(||)和批次标题检查完成。具体如何我在代码的注释部分,特别注意括号。

我在this link处看到了解决方案,当我尝试它时,该解决方案有效。还有其他人提到,这不适合你想要的。

相关问题