2013-12-08 95 views
9

我是新来的编程和C#语言。我卡住了,请帮忙。所以我写了这个代码(C#的Visual Studio 2012):如何检查dataGridView复选框是否被选中?

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 
     } 
    } 
} 

所以我得到以下错误:

操作“==”不能应用于类型的“对象”和操作数“布尔”。

回答

4

值返回一个对象类型,并且不能与布尔值进行比较。你可以投的值bool

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

.Cells [1]数字代表什么? –

27

您应该使用Convert.ToBoolean()检查的dataGridView复选框被选中。

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 
     } 
    } 
} 
+0

这是比接受的答案更好的方法...'Convert.ToBoolean()'不需要'null'值检查,因此也简化了代码。 –

4

所有在这里的答案是容易出错,

因此,要澄清一些事情对谁碰到这个问题绊倒人,

的最佳方式来达到OP想要什么是下面的代码:

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! 
     } 
    }    
} 
+1

为我工作.. –

0

轻微的修改应该工作

if (row.Cells[1].Value == (row.Cells[1].Value=true)) 
{ 
    // what I want to do 
} 
0
if (Convert.ToBoolean(row.Cells[1].EditedFormattedValue)) 
{ 
    //Is Checked 
} 
+1

这不提供问题的答案。一旦你有足够的[声誉](https://stackoverflow.com/help/whats-reputation),你将可以[对任何帖子发表评论](https://stackoverflow.com/help/privileges/comment);相反,[提供不需要提问者澄清的答案](https://meta.stackexchange.com/questions/214173/why-do-i-need-50-reputation-to-comment-what-c​​an- I-DO-代替)。 - [来自评论](/ review/low-quality-posts/16750699) –

+0

**来自评论队列:**我可以请求您请您在答案中添加更多的上下文。仅有代码的答案很难理解。如果您可以在帖子中添加更多信息,它可以帮助提问者和未来的读者。另请参阅[完全解释基于代码的答案](https://meta.stackexchange.com/questions/114762/explaining-entirely-code-based-answers)。 –

+0

请查看[如何回答](https://stackoverflow.com/help/how-to-answer)并更新您的答案以提供更多详细信息。具体来说,如果你解释了如何解决这个问题,这将会很有帮助 – Ortund

相关问题