日期:2014-05-17  浏览次数:20922 次

对C#的datagridview操作有点疑问
下面的代码是动态添加一个column,然后自动设置勾选,但是为啥运行之后没有一个是已经被勾选的了呢??
在MesageBox里明明有2个显示已经勾选了。。。

C# code
                DataGridViewCheckBoxColumn c = new DataGridViewCheckBoxColumn();
                c.HeaderText = "Mise En Vente";
                c.Width = 150;
                c.Name = "venteCheckBox";
                dataGridViewOeuvres.Columns.Add(c);
                
                for(int i=0; i<  dataGridViewOeuvres.RowCount; ++i)
                {
                    CheckBox ck = new CheckBox();
                    ck.Checked = Convert.ToInt32(dataGridViewOeuvres.Rows[i].Cells["miseEnVente"].Value)>0?true:false;
                    dataGridViewOeuvres.Rows[i].Cells["venteCheckBox"].Value = ck;
                    MessageBox.Show(dataGridViewOeuvres.Rows[i].Cells["venteCheckBox"].Value.ToString());
                }

            dataGridViewOeuvres.CellClick += DataGridCellClick;




还有就是事件处理里,不知道为什么报NullReference错误。。。
C# code
        void DataGridCellClick(object sender, DataGridViewCellEventArgs e)
        {
            
            if(dataGridViewOeuvres.Columns[e.ColumnIndex].Name == "venteCheckBox")
            {
                MessageBox.Show(dataGridViewOeuvres.Rows[e.RowIndex].Cells["venteCheckBox"].Value.ToString());
            }
        }


------解决方案--------------------
探讨

dataGridViewOeuvres.Rows[i].Cells["venteCheckBox"].Value = 1;//选中
你后面null错误,自己调试,看看带索引的地方的对象是否存在
特别是e.RowIndex,可能是-1,即标题行

------解决方案--------------------
private void Form1_Load(object sender, EventArgs e)
{
dataGridView1.RowCount = 5;

DataGridViewCheckBoxColumn c = new DataGridViewCheckBoxColumn();
c.HeaderText = "Mise En Vente";
c.Width = 150;
c.Name = "venteCheckBox";
dataGridView1.Columns.Add(c);
for (int i = 0; i < dataGridView1.RowCount; i++)
{
dataGridView1.Rows[i].Cells[0].Value=i;
CheckBox ck = new CheckBox();
ck.Checked=(Convert.ToInt32(dataGridView1.Rows[i].Cells[0].Value)>0 ? true: false);
dataGridView1.Rows[i].Cells["venteCheckBox"].Value = ck.Checked;
}
dataGridView1.CellClick+=new DataGridViewCellEventHandler(dataGridView1_CellClick);
}
private void dataGridView1_CellClick(object sender, DataGridViewCellEventArgs e)
{
if (dataGridView1.Columns[e.ColumnIndex].Name == "venteCheckBox")
MessageBox.Show(Convert.ToString(dataGridView1.Rows[e.RowIndex].Cells["venteCheckBox"].Value));
}


------解决方案--------------------
dataGridViewOeuvres.Rows[i].Cells["venteCheckBox"].Value = ck;
怎么一个值会等一个checkBox?
------解决方案--------------------
同上,你的程序得调试下。。逐步调试就可以看到到底哪里错了。。跟踪参数的变化就知道了啊