C# datagridview添加复选框后,如何操作

问题遇到的现象和发生背景

在datagridview中添加了复选框,现在想要把选中的数据填入textbox中

问题相关代码,请勿粘贴截图

private void dataGridView1_CellMouseClick(object sender, DataGridViewCellMouseEventArgs e)
{
//不是序号列和标题列时才执行
if (e.RowIndex != -1 && e.ColumnIndex != -1)
{
//checkbox 勾上
if ((bool)dataGridView1.Rows[e.RowIndex].Cells[0].EditedFormattedValue == true)
{
//选中改为不选中
this.dataGridView1.Rows[e.RowIndex].Cells[0].Value = false;
}
else
{
//不选中改为选中
this.dataGridView1.Rows[e.RowIndex].Cells[0].Value = true;
}
}
}

运行结果及报错内容

img

我的解答思路和尝试过的方法
我想要达到的结果

img


如上图,现在想要达到的结果就是textbox中,除了数量是选中的几列中的数量相加,其他的都显示datagridview选中的第一行的数据

很简单实现的,如有帮助,请采纳

        private void dataGridView1_CellMouseClick(object sender, DataGridViewCellMouseEventArgs e)
        {
            //不是序号列和标题列时才执行
            if (e.RowIndex != -1 && e.ColumnIndex != -1)
            {
                //checkbox 勾上
                if ((bool)dataGridView1.Rows[e.RowIndex].Cells[0].EditedFormattedValue == true)
                {
                    //选中改为不选中
                    this.dataGridView1.Rows[e.RowIndex].Cells[0].Value = false;
                   
                    //没有选中,你可以自己清空控件状态
                }
                else
                {
                    //不选中改为选中
                    this.dataGridView1.Rows[e.RowIndex].Cells[0].Value = true;

                    int sum = 0;
                    for (int i = 0; i < dataGridView1.RowCount; i++)
                    {
                        if ((bool)dataGridView1.Rows[i].Cells[0].EditedFormattedValue == true)
                        {
                            //选中状态参与计算
                            sum += int.Parse(dataGridView1.Rows[e.RowIndex].Cells[4].ToString());
                        }
                    }

                    text_数量控件.Text = sum.ToString();

                    //其他控件
                    text_项目编码控件.Text = dataGridView1.Rows[e.RowIndex].Cells[1].Value.ToString();       //项目编码
                    text_名称控件.Text = dataGridView1.Rows[e.RowIndex].Cells[2].Value.ToString();       //名称
                    text_出货日.Text = dataGridView1.Rows[e.RowIndex].Cells[2].Value.ToString();       //出货日
                }
            }
        }

你应该在选中事件中做数量的加法。第一个图没有选中,checkBox 为false。所以没计算结果。

你写个方法,循环读取Grid,每次点击复选框执行一次:

判断值是否改变ValueChange方法
isone=true;是否第一行。

for(int i=1;i<=this.dataGridView1.rowcount;i++){
if isone=true;
{
isone=false;
this.品名.value= this.dataGridView1.Rows[RowIndex].Cells[1].Value;
this.项目编码.value= this.dataGridView1.Rows[RowIndex].Cells[2].Value;
this.数量.value= this.dataGridView1.Rows[RowIndex].Cells[3].Value;
}
else
{
this.数量.value=this.数量.value+ this.dataGridView1.Rows[RowIndex].Cells[3].Value;
}

}


把代码加到你的dataGridView1_CellMouseClick最下面