簡體   English   中英

如何檢查是否選中了 dataGridView checkBox?

[英]How to check if dataGridView checkBox is checked?

我是編程和 C# 語言的新手。 我卡住了,請幫忙。 所以我寫了這段代碼(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
         }
    }
}

所以我收到以下錯誤:

運算符“==”不能應用於“object”和“bool”類型的操作數。

您應該使用Convert.ToBoolean()來檢查是否選中了 dataGridView checkBox。

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

這里的所有答案都容易出錯,

所以為了讓那些偶然發現這個問題的人澄清事情,

實現 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!
        }  
    }              
}

值返回一個對象類型,不能與布爾值進行比較。 您可以將值轉換為 bool

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

稍微修改應該工作

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

上面這段代碼是錯誤的!

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

    // Note: Can't check cell.value for null if Cell is null 
    // just check cell != null first
    //We don't want a null exception!
    if (cell.Value != null)
    {
        if (cell.Value == cell.TrueValue)
        {
           //It's checked!
        }  
    }              
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM