2013-06-20 98 views
-1

问题是,当我通过RowTemplate.DefaultCellStyle.SelectionBackColor在我的窗体构造函数中更改所选行的颜色时,它可以工作,但在用户单击某些按钮以更改所选网格时,它不起作用背色! 请任何帮助!动态更改datagridview选择颜色c#

public Form1() 
{ 
    InitializeComponent(); 
    dataGridView1.RowTemplate.DefaultCellStyle.SelectionBackColor=Color.Red; //this  works fine 
} 
void button2_Click(object sender, EventArgs e) 
{ 
    dataGridView1.RowTemplate.DefaultCellStyle.SelectionBackColor=Color.Blue;//but this does not work 
} 

回答

1

试试这个..

void dataGridView1_RowPrePaint(object sender, 
    DataGridViewRowPrePaintEventArgs e) 
{ 
    If (DatagridView1.Rows(DataGridView1.CurrentCell.RowIndex).Selected) 
    { 

    DataGridView1.Rows(DataGridView1.CurrentCell.RowIndex).DefaultCellStyle.SelectionBackColor=Color.Blue; 

    } 
} 
+0

的EventArgs没有RowIndex属性!!!!! –

+0

@IsaacShakiba .. Sorrrryy !!从您的代码复制粘贴错误:P ..其''更新..再次.. .. – matzone

+0

我不想改变选择回颜色暂时! –

0
void button2_Click(object sender, EventArgs e) 
{ 
    foreach (DataGridViewRow row in dataGridView1.Rows) 
    { 
     row.DefaultCellStyle.SelectionBackColor = Color.Blue 
    } 
} 

更新:

void button2_Click(object sender, EventArgs e) 
{ 
    foreach (DataGridViewColumn col in dataGridView1.Columns) 
    { 
     col.DefaultCellStyle.BackColor = Color.Blue 
    } 
} 
+0

这段代码改变了现有行的选择颜色,当一行被添加到网格时,选择的背景颜色变为默认颜色! –

+0

我更新了我的答案 –