【问题标题】:Check DatagridviewCheckboxCell - c#检查 DatagridviewCheckboxCell - c#
【发布时间】:2023-04-07 08:44:01
【问题描述】:

我有 3 个 DatagridviewCheckboxCell,我用这段代码来检查它们:

foreach (DataGridViewRow row in dataGridView1.Rows)
        {
            DataGridViewCheckBoxCell chk1 = (DataGridViewCheckBoxCell)row.Cells["Column6"];
            DataGridViewCheckBoxCell chk2 = (DataGridViewCheckBoxCell)row.Cells["Column7"];
            DataGridViewCheckBoxCell chk3 = (DataGridViewCheckBoxCell)row.Cells["Column8"];

            string commande2 = "SELECT id_pres from Fonct_Prest where id_fonc = @id";
            OleDbCommand cmd2 = new OleDbCommand(commande2, con);
            cmd2.Parameters.AddWithValue("@id", row.Cells["Code"].Value);
            dt2.Load(cmd2.ExecuteReader());

            for (int i = 0; i < dt2.Rows.Count; i++)
            {
                if (dt2.Rows[i][0].ToString() == "1")
                {
                    chk1.Value = true;
                }
                if (dt2.Rows[i][0].ToString() == "2")
                {
                    chk2.Value = true;
                }
                if (dt2.Rows[i][0].ToString() == "6")
                {
                    chk3.Value = true;
                }
            }
            cmd2.Parameters.Clear();
            dt2.Rows.Clear();
        }

此代码工作正常,但在 datagridview 的第一行中,未选中复选框。我的代码哪里出错了?

【问题讨论】:

    标签: c# datagridviewcheckboxcell


    【解决方案1】:

    如果你知道列名,你可以试试这段代码。

        private void button2_Click(object sender, EventArgs e)
        {
            for(int i = 0; i < dataGridView1.RowCount; i++)
            {
                //Set defined value
                //dataGridView1.Rows[i].Cells["Column2"].Value = true;
    
                //toggle value from checked to unchecked.
                dataGridView1.Rows[i].Cells["Column2"].Value = !Convert.ToBoolean(dataGridView1.Rows[i].Cells["Column2"].Value);
            }
        }
    

    【讨论】:

    • 我试过这个但同样的行为,datagridview 第一行的复选框没有选中
    猜你喜欢
    • 1970-01-01
    • 2013-07-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多