簡體   English   中英

更改單元格值C#后如何在線更改datagridview中的行顏色?

[英]How to change row color in datagridview online after change cell value C#?

輸入單元格值時如何更改datagridview中的行顏色,我使用了以下代碼和cellFormatting事件,但是當輸入下限和上限之間的值時,它給出的錯誤輸入字符串格式不正確

private void dgvResult_CellFormatting(object sender, DataGridViewCellFormattingEventArgs e)
        {

            if (dgvResult.Rows[e.RowIndex].Cells["Result"].Value == DBNull.Value)
            {
                e.CellStyle.BackColor = Color.LightSkyBlue;
            }

            else if (Convert.ToInt32(dgvResult.Rows[e.RowIndex].Cells["Result"].Value.ToString()) >= Convert.ToInt32(dgvResult.Rows[e.RowIndex].Cells["Lower Limit"].Value.ToString()) &&
            Convert.ToInt32(dgvResult.Rows[e.RowIndex].Cells["Result"].Value.ToString()) <= Convert.ToInt32(dgvResult.Rows[e.RowIndex].Cells["Upper Limit"].Value.ToString()))
            {
                e.CellStyle.BackColor = Color.LightSkyBlue;
            }

            else if (Convert.ToInt32(dgvResult.Rows[e.RowIndex].Cells["Result"].Value) < Convert.ToInt32(dgvResult.Rows[e.RowIndex].Cells["Lower Limit"].Value) ||
                Convert.ToInt32(dgvResult.Rows[e.RowIndex].Cells["Result"].Value) > Convert.ToInt32(dgvResult.Rows[e.RowIndex].Cells["Upper Limit"].Value))
            {
                e.CellStyle.BackColor = Color.LightSalmon;
            }
        }

這個 CellFormatting 是正確的事件還是我可以使用另一個事件來解決這個問題並在鍵入結果值並將其與下限值和上限值進行比較后更改行顏色?

問題是由於某種原因,您的值之一不是 int,請嘗試使用此代碼

private void dgvResult_CellFormatting(object sender, DataGridViewCellFormattingEventArgs e)
{
    if (dgvResult.Rows[e.RowIndex].Cells["Result"].Value == DBNull.Value)
    {
        e.CellStyle.BackColor = Color.LightSkyBlue;
    }
    else
    {
        int cellValue = 0;
        int lowerLimit = 0;
        int upperLimit = 0;
        if (int.TryParse(dgvResult.Rows[e.RowIndex].Cells["Result"].Value.ToString(), out cellValue) 
            && int.TryParse(dgvResult.Rows[e.RowIndex].Cells["Lower Limit"].Value.ToString(), out lowerLimit)
            && int.TryParse(dgvResult.Rows[e.RowIndex].Cells["Upper Limit"].Value.ToString(), out upperLimit)
            )
        {
            if(cellValue >= lowerLimit && cellValue <= upperLimit)
                e.CellStyle.BackColor = Color.LightSkyBlue;
            else
                e.CellStyle.BackColor = Color.LightSalmon;
        }
        else
        {
            // The cell value is not an int..
            e.CellStyle.BackColor = Color.LightSalmon;
        }
    }
}

在“// The cell value is not an int..”之后的行上放置一個斷點,然后查看您正在使用的單元格中的值。

暫無
暫無

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

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