简体   繁体   中英

C# Winforms: Customize DataGridView selected gridcolor

I have DataGridView which has 3 columns and 3 rows. If user selects one row, I want to make the grids of that row to change color. I'm completely new to C# and I cant figure out how can I achieve my goal. Please help me out. Thanks

I understand that you are asking about modifying the appearance of the cells' GridLines and doing it individually .

According to MSDN this is possible. However it seems to involve a real big effort. You would need to subclass the DataGridview and modify the example code extensively to work dynamically. After toying with it for a while I decided, that it isn't worth it. I suggest going for one of the other ways to mark the selection. (Or gain a lot of rep and put a bounty on it..)

Looking at the properties of the DataGridView class, you have the option to set the grid color in the DataGridView.GridColor property.

Gets or sets the color of the grid lines separating the cells of the DataGridView.

Example below:

dataGridView1.GridColor = SystemColors.ActiveBorder;

You can change it using DataGridView.GridColor property. This will change the color of the grid lines. See the link - DataGridView.GridColor

 dataGridView1.GridColor = SystemColors.Blue;

This will change every line in the grid. Can you specify what exactly of the row you want to change? I presume you want only the lines of the row. If you want to change only the row lines color, than you can use the following code:

dataGridView1.Rows[0].DefaultCellStyle.BackColor = Color.Red;
dataGridView1.Rows[0].DefaultCellStyle.ForeColor = Color.White;

Below you can see it used in CellClick event on the row:

private void dataGridView1_CellClick(object sender, DataGridViewCellEventArgs e)
{
    DataGridView dgv = sender as DataGridView;
    if (dgv == null)
        return;
    if (dgv.CurrentRow.Selected)
    {
        dataGridView1.Rows[0].DefaultCellStyle.BackColor = Color.Red;
        dataGridView1.Rows[0].DefaultCellStyle.ForeColor = Color.White;
    }
}

Hope this helps you.

DataGridViewRow dgRow = dataGridView1.Rows[e.RowIndex];
dgRow.DefaultCellStyle.BackColor = Color.Red; 
dgRow.DefaultCellStyle.ForeColor = Color.Yellow;

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