木子屋 Dnawo's BLOG

MDI子窗体Load事件中设置DataGridView行高、背景色失效!

👤 dnawo 📅 2009-10-13 👁 5471 👍 0 💬 0 🔄 本站原创
在窗体的Load事件中设置DataGridView行高、背景色代码:

private void Form2_Load(object sender, EventArgs e)
{
    using (SqlConnection conn = new SqlConnection("server=(local);database=Northwind;user id=sa;password=sa;"))
    {
        using (SqlDataAdapter adapter = new SqlDataAdapter("Select * FROM Products", conn))
        {
            DataTable table = new DataTable();
            adapter.Fill(table);

            dataGridView1.DataSource = table;
        }
    }

    //设置第一行高度、背景色
    dataGridView1.Rows[0].Height = 100;
    dataGridView1.Rows[0].DefaultCellStyle.BackColor = Color.Red;
}

若窗体不是MDI子窗体,上边代码能正常运行;当窗体做为MDI子窗体时,数据绑定正常,但不能设置行高和背景色!获取设置后的值:

private void button1_Click(object sender, EventArgs e)
{
    MessageBox.Show(dataGridView1.Rows[0].Height.ToString() + "\r\n" + dataGridView1.Rows[0].DefaultCellStyle.BackColor.ToString());
    /*
     * 结果:
     * 
     * 23
     * Color[Empty]
    */
}

说明设置未生效!后测试发现,若在按钮点击事件中设置DataGridView行高、背景色却又可以:

private void button1_Click(object sender, EventArgs e)
{
    //设置第一行高度、背景色
    dataGridView1.Rows[0].Height = 100;
    dataGridView1.Rows[0].DefaultCellStyle.BackColor = Color.Red;

    MessageBox.Show(dataGridView1.Rows[0].Height.ToString() + "\r\n" + dataGridView1.Rows[0].DefaultCellStyle.BackColor.ToString());
    /*
     * 结果:
     * 
     * 100
     * Color[Red]
    */
}

暂未找到原因!

评论(0)

暂无评论。

计算题
评论需审核通过后显示
← 上一篇 ComboBox手工添加数据示例 下一篇 → 2009胡润百富榜