簡體   English   中英

Datagridview單元格樣式問題

[英]Datagridview Cell Style issue

我在C#桌面應用程序中有一個Datagridview 當任何一個單元格為空時,為了突出顯示它,我將該特定單元格的背景更改為Color.Green

                if (checkString(Convert.ToString(this.UserDataTable.Rows[i].Cells[kk].Value).Trim()) == false)
                {
                    this.UserDataTable.Rows[i].Cells[kk].Style.BackColor = Color.Green;
                    this.MandatoryField_Label.ForeColor = Color.Green;
                    success = false;
                }

當用戶在單元格中輸入數據時,我將還原所做的更改。 任何想法如何做到這一點。

我正在考慮的解決方案之一是檢查每種單元格的顏色,然后進行更改。 我敢肯定,有更好的方法可以做到這一點。

這不起作用:

 this.UserDataTable.DefaultCellStyle.BackColor = Color.White;

謝謝

您可以在CellLeave事件中檢查單元格的內容

if(!string.IsNullOrEmpty(((DataGridViewCell)sender).Value))
    ((DataGridViewCell)sender).Style.BackColor = Color.White;

解決此問題的最干凈的方法可能是使用像這樣的CellFormatting事件(這是您唯一需要的代碼,您可以刪除其他代碼):

dataGridView1.CellFormatting += new DataGridViewCellFormattingEventHandler(dataGridView1_CellFormatting);

void dataGridView1_CellFormatting(object sender, DataGridViewCellFormattingEventArgs e)
{
    if (e.Value == null || String.IsNullOrWhiteSpace(e.Value.ToString()))
    {
        e.CellStyle.BackColor = Color.Green;
    }
    else
    {
        e.CellStyle.BackColor = Color.White;
    }            
}

暫無
暫無

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

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