C# winform datagridview 复选

在Web程序中数据源绑定控件GridView中有模板列,而要获取其中的复选框是否选中以及复选框所在的行是很简单的,经典代码如下:
     for(int i=0;i<gvList.Rows.Count;i++)
     {
         if(((CheckBox)gvList.Rows[i].Cells[0].FindControl("chkID")).Checked)
         { }
     }
         但是在WinForm中的DataGridView控件却不能这样来做,DataGridView控件根本没有自由模板列,有的是6个内置模板列,而复选框正是其中之一。要获得复选框是否选中以及选中行对应的其他值是不能按照Web程序中的这种方式来实现的,而是需要通过DataGridView控件中Cells单元格的Value属性来判断的。

        (WinForm中DataGridView控件通过复选框实现多条记录的删除)代码如下:
         private void btnDelete_Click(object sender, EventArgs e)
         {
             string strNames = "您选择的是:";
             for(int i=0;i<dgvList.Rows.Count;i++)
             {
                 if (dgvList.Rows[i].Cells[0].Value != null) //判断该行的复选框是否存在
                 {
                     if (dgvList.Rows[i].Cells[0].Value.ToString() == "True") //判断该复选框是否被选中
                     {
                         strNames += dgvList.Rows[i].Cells[2].Value.ToString() + "   ";
                     }
                 }
             }
             MessageBox.Show(strNames, "系统提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
         }
         运行结果如图所示:

 转载自网络,来源不明!!

原文地址:https://www.cnblogs.com/moss_tan_jun/p/2010022.html