简体   繁体   中英

C# if condition for character cell value in datagridview

I'm having a coding problem in how can i check this to work with a character value instead of an integer? The code works if condition value is an integer but the cell value contains either 'I' or 'A'. I tried cellvalue.split but gives me an error.

if (int.Parse(cellvalue.Value.ToString()) == 'A')
                    statcell.Value = Properties.Resources.icons8_login_rounded_filled_100;
                else
                    statcell.Value = Properties.Resources.icons8_folder_50;

Here's the overall code:

        private void dg_vw_actve_doc_CellValueChanged(object sender, DataGridViewCellEventArgs e)
        {
            if (e.ColumnIndex == 0 && !isInit)
            {
                var valueCell = dg_vw_actve_doc.Rows[e.RowIndex].Cells[e.ColumnIndex];
                var imgCell = dg_vw_actve_doc.Rows[e.RowIndex].Cells[e.ColumnIndex + 0 ]; 
                char firstCharacterInCell = valueCell.Value.ToString()[1];
                if (firstCharacterInCell == 'A')
                    imgCell.Value = Color.Green;
                else
                    imgCell.Value = Color.Red;
            }
        }

My imgCell variable is a column value that was added from datagridview with a columnindex of 0, while my valueCell variable has a column index of 1 and is not added from datagridview in editor and only appears during runtime. It's an unbound column

Your int.Parse call is returning an integer, not a character.

You can get the first element of the char array of the string. This one would be useful if you later would need to use that char:

// Check if there was no data
if (cellvalue.Value.ToString() != string.Empty)
{
    char firstCharacterInCell = cellvalue.Value.ToString()[0];
    if (firstCharacterInCell == 'A' || firstCharacterInCell == 'I')
    {
        // Your condition is matched
    }
}

You can alternatively check if the string starts with an 'I' or an 'A'

string cellContent = cellvalue.Value.ToString();
if (cellContent.StartsWith("A") || cellContent.StartsWith("I"))
{
    // Your condition is matched
}

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