2013-06-20 132 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

我更新了我的答案 –