简体   繁体   中英

C# - How to get cell value from DataGridView?

I'm using a three columns DataGridview. Two columns are filled by data read with SQL.

The third column is a checkbox.

I tried to use these two code snippets:

for (int i=0, i<datagrid.RowCount; i++)
{
    if (datagrid.Rows[i].Cells[0].Value.Equals(true))
    {
        string name=datagrid.Rows[i].Cells[1].Value.ToString();
    }
}
for (int i=0, i<datagrid.RowCount; i++)
{
    if (datagrid.Rows[i].Cells[0]=true) 
    {
        string name=datagrid.Rows[i].Cells[1].Value.ToString();
    }
}

In the second case, I get an error that it is impossible to convert "bool" in "system.windows.forms.datagridviewcell".

You can get cell value from property "Value" in DataGridViewCell object that's explained if official API doc

And of course you can't convert the DataGridViewCell to boolean type or assign to DataGridViewCell variable, a boolean type variable. C# a strongly typed language.

Here at datagrid.Rows[i].Cells[0]=true you are trying to assign that datagrid.Rows[i].Cells[0] now is 'True', but in strong typed language you can't do it.

Firstly, datagrid.Rows[i].Cells[0] == true now you are compare, and even this is not good (at all).

Probably you are trying to check cell is exists or something in this matter, but this is other question.

If you want to get value from cell, just do it as that explained above and work with that.

If you want to get a single checked row the following provides that.

DataGridViewRow checkedRow = datagrid.Rows.Cast<DataGridViewRow>()
    .FirstOrDefault(row => Convert.ToBoolean(row.Cells[0].Value));
if (checkedRow != null)
{
    
    MessageBox.Show($"{checkedRow.Cells[1].Value.ToString()} on row {checkedRow.Index}");
}
else
{
    MessageBox.Show("Nothing checked");
}   

For obtaining all checked rows

var checkedRows = datagrid.Rows.Cast<DataGridViewRow>()
    .Where(r => Convert.ToBoolean(r.Cells["Selected"].Value) ).ToList();

if (checkedRows.Count >0)
{
    for (int index = 0; index < checkedRows.Count; index++)
    {
        Console.WriteLine(checkedRows[index].Cells[1].Value.ToString());
    }
}
else
{
    // no checked rows
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM