下面的代码是动态添加一个column,然后自动设置勾选,但是为啥运行之后没有一个是已经被勾选的了呢??
在MesageBox里明明有2个显示已经勾选了             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错误
        void DataGridCellClick(object sender, DataGridViewCellEventArgs e)
        {
        
         if(dataGridViewOeuvres.Columns[e.ColumnIndex].Name == "venteCheckBox")
         {
         MessageBox.Show(dataGridViewOeuvres.Rows[e.RowIndex].Cells["venteCheckBox"].Value.ToString());
         }
        }

解决方案 »

  1.   

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

  2.   

    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));
            }
      

  3.   

    dataGridViewOeuvres.Rows[i].Cells["venteCheckBox"].Value = ck;
    怎么一个值会等一个checkBox?
      

  4.   

    在Null错误里,我的RowIndex是0-x, 问题出在ColumnsIndex上。因为在这个GridView里有2个Columns是隐藏的当我点击后在可视的窗口上应该是3但是得到的index是5.。。不知道是不是这个问题那个值的类型是Object说明可以是任何类型,我在上面加入了DataGridViewCheckBoxColumn,那么这里应该就可以直接赋予Checkbox
      

  5.   

    还有就是我试了LS的办法都没用。 奇怪的是,我在赋予Checkbox后查看GridView里的值是已经勾选了的