如何在datagridView中获取Row索引和列索引

时间:2013-08-05 08:35:25

标签: c# winforms checkbox datagridview

我的问题是:当我点击一些Checkbox时,如何从DataGridView获取当前复选框控件的索引 这是我的snick代码

dataGridView2.RowCount = 5;
    dataGridView2.ColumnCount = 4;

    for (int i = 0; i < dataGridView2.ColumnCount; i++)
    {
        for (int j = 0; j < dataGridView2.RowCount; j++)
        {
            box = new CheckBox();
            box.Text = "MyDate";
            //box.Size = new System.Drawing.Size(15, 15);
            dataGridView2.Controls.Add(box);
            Rectangle rec = dataGridView2.GetCellDisplayRectangle(i, j, true);
            box.Left = rec.Left;
            box.Top = rec.Top;
        }
    }
}

3 个答案:

答案 0 :(得分:0)

如果您使用CellContentClick事件或您获得DataGridViewCellEventArgs的任何其他事件,则您拥有ColumnIndexRowIndex属性,这些属性是细胞改变了

答案 1 :(得分:0)

检查此链接。这为您提供了有关网格视图的详细信息。

http://msdn.microsoft.com/en-us/library/ms972814.aspx

http://msdn.microsoft.com/en-us/library/aa479344.aspx

答案 2 :(得分:0)

看起来您尝试在不使用CheckBox的情况下向DataGridView添加纯DataGridViewCheckBoxColumn es,此方法的解决方案很简单:

for (int i = 0; i < dataGridView2.ColumnCount; i++)
    {
        for (int j = 0; j < dataGridView2.RowCount; j++)
        {
            box = new CheckBox();
            box.Text = "MyDate";
            //box.Size = new System.Drawing.Size(15, 15);
            dataGridView2.Controls.Add(box);
            Rectangle rec = dataGridView2.GetCellDisplayRectangle(i, j, true);
            box.Left = rec.Left;
            box.Top = rec.Top;
            //Added code
            box.Tag = new Point(i,j);
            box.Click += CheckBoxesClicked;
        }
    }
private void CheckBoxesClicked(object sender, EventArgs e){
   CheckBox chb = sender as CheckBox;
   if(chb.Tag != null) {
      Point coord = (Point)chb.Tag;
      MessageBox.Show(string.Format("Row index: {0}\nColumn index: {1}", coord.Y, coord.X);
   }
}     

您应该使用DataGridViewCheckBoxColumn代替,使用该方法,您可以处理事件CellContentClick ......