How to check if dataGridView checkBox is checked?

断了今生、忘了曾经 提交于 2019-12-30 06:04:16

问题


I'm new to programming and C# language. I got stuck, please help. So I have written this code (c# Visual Studio 2012):

private void button2_Click(object sender, EventArgs e)
{
    foreach (DataGridViewRow row in dataGridView1.Rows)
    {
         if (row.Cells[1].Value == true)
         {
              // what I want to do
         }
    }
}

And so I get the following error:

Operator '==' cannot be applied to operands of type 'object' and 'bool'.


回答1:


You should use Convert.ToBoolean() to check if dataGridView checkBox is checked.

private void button2_Click(object sender, EventArgs e)
{
    foreach (DataGridViewRow row in dataGridView1.Rows)
    {
         if (Convert.ToBoolean(row.Cells[1].Value))
         {
              // what you want to do
         }
    }
}



回答2:


All of the answers on here are prone to error,

So to clear things up for people who stumble across this question,

The best way to achieve what the OP wants is with the following code:

foreach (DataGridViewRow row in dataGridView1.Rows)
{
    DataGridViewCheckBoxCell cell = row.Cells[0] as DataGridViewCheckBoxCell; 

    //We don't want a null exception!
    if (cell.Value != null)
    {
        if (cell.Value == cell.TrueValue)
        {
           //It's checked!
        }  
    }              
}



回答3:


Value return an object type and that cannot be compared to a boolean value. You can cast the value to bool

if ((bool)row.Cells[1].Value == true)
{
    // what I want to do
}



回答4:


Slight modification should work

if (row.Cells[1].Value == (row.Cells[1].Value=true))
{
    // what I want to do
}



回答5:


if (Convert.ToBoolean(row.Cells[1].EditedFormattedValue))
{
    //Is Checked
}


来源:https://stackoverflow.com/questions/20452844/how-to-check-if-datagridview-checkbox-is-checked

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!