datagridview设置属性无效,datagridview属性
DataTable Table = new DataTable();
DataColumn dc = null;
dc = Table.Columns.Add("PlanID", Type.GetType("System.String"));
dc = Table.Columns.Add("序号", Type.GetType("System.String"));
DataRow newRow;
newRow = Table.NewRow();
newRow[0] = "PlanID11";
newRow[1] = "序号22";
Table.Rows.Add(newRow);
dataGridView1.DataSource = Table;
dataGridView1.Rows[0].ReadOnly = true;
dataGridView1.Rows[0].DefaultCellStyle.BackColor = Color.Aqua;
相同的代码, 在第一个窗口运行正常,复制到第二个窗口 最后两句无效
dataGridView1.Rows[0].ReadOnly = true;
dataGridView1.Rows[0].DefaultCellStyle.BackColor = Color.Aqua;
单步执行正常,但是运行结果就像没有执行一样.
说明一下:是在Form_Load()里面写的
解决方案
你的代码,我可以重现这个问题。
解决方法是, 把设置 color 的那段代码,放在databindingCompleted 事件里,以确保绑定完成之后再设置:
void dataGridView1_DataBindingComplete(object sender, DataGridViewBindingCompleteEventArgs e)
{
dataGridView1.Rows[0].DefaultCellStyle.BackColor = Color.Yellow;
}
当设置mdi parent 之后,它会重新刷新这个form,让其在 mdiclient 里面显示出来,会重新把所有绑定的数据在显示一遍,这里有一点延时,导致颜色其实没有设置到正确显示的row上。在DatabindingCompleted 时间里面,确保所有的数据 都已经绑定完成,这时候 能够确保 设置在正确的 行上面。
有一点需要注意的,当绑定列和非绑定列在一起,有一些非绑定列的 值,行的颜色也会丢失(比如当你对某一列进行排序)。在排序的时候也会触发DataBindingCompleted 事件。 你也可以用 dictionary 去保存值(详见FAQ 29.如何同时显示绑定和非绑定数据?)
用户评论