开发者

properties applying only after mouse click in datagrid in C# winforms

i used code like this to change color of cell but properties applying only after mouse click but i want change color after form loaded

Used Code

    private void dataGridView1_RowValidated(object sender, DataGridViewCellEventArgs e)
    {
        for (int i = 0; i < 5; i++)
        {
            int j = 6;
            DataGridViewCellStyle CellStyle = new DataGridViewCel开发者_开发技巧lStyle();
            CellStyle.ForeColor = Color.Red;
            dataGridView1[j, i].Style = CellStyle;
        }
    }


Remove that code from dataGridView1_RowValidated and add it to form Load event instead:

Add this code in the form constructor:

public Form1()
{
    InitializeComponents();

    this.Load += OnFormLoad;
    this.dataGridView1.Sorted += OnDataGridSorted;
}

private void OnFormLoad(object sender, EventArgs e)
{
    UpdateDataGridViewColor();
}

private void OnDataGridSorted(object sender, EventArgs e)
{
    UpdateDataGridViewColor(); 
}

private void UpdateDataGridViewColor()
{
    for (int i = 0; i < 5; i++)
    {
        int j = 6;
        DataGridViewCellStyle CellStyle = new DataGridViewCellStyle();
        CellStyle.ForeColor = Color.Red;
        dataGridView1[j, i].Style = CellStyle;
    }
}

Note also you can add form Load event by double click on the form designer..

Edit: you stated in comments that when you click column to sort the applying color will removed. to fix that add this.dataGridView1.Sorted += OnDataGridSorted; event so whenever sorted is done the new style is applied. the code above updated. "btw: I don't tested it, till me if it not worked.."

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜