【问题标题】:Delete selected rows from datagridview从 datagridview 中删除选定的行
【发布时间】:2015-05-04 14:36:48
【问题描述】:

如果复选框列按钮在该行中被选中,我正在创建一个列表以添加第一列中的项目。当弹出消息框询问我是否确定是否要删除时,它显示的值是“DataGridViewRow {Index = 0}”而不是第一列的值。有没有我缺少的类型转换?

private void button1_Click(object sender, EventArgs e)
    {
        List<DataGridViewRow> selectedRows = (from newRow in DGV1.Rows.Cast<DataGridViewRow>() where Convert.ToBoolean(newRow.Cells["Delete"].Value) == true select newRow).ToList();
        var message = string.Join(Environment.NewLine, selectedRows);
        if (MessageBox.Show("Are you sure you want to delete users:\n" + message, "Warning", MessageBoxButtons.YesNo, MessageBoxIcon.Warning) == DialogResult.Yes)
        {
        for (int x = 0; x < DGV1.RowCount - 1; x++)
        {
            if (Convert.ToBoolean(DGV1.Rows[x].Cells[0].Value))
            {


                    foreach (DataGridViewRow newRow in selectedRows)
                    {

                        using (SqlCommand cmd = new SqlCommand("DELETE FROM JoshUserTable WHERE UserID = @UserID", con))
                        {
                            cmd.CommandType = CommandType.Text;
                            cmd.Parameters.AddWithValue("@UserID", newRow.Cells["UserID"].Value);

                            cmd.ExecuteNonQuery();

                            DGV1.Rows.Remove(newRow);
                        }

                    }
                }
            }
        }

【问题讨论】:

  • 在迭代行时删除行?那是潜在的麻烦。不知道我理解为什么你的代码中有两个循环——看起来你只需要 selectedRows 循环。

标签: c# checkbox datagridview


【解决方案1】:

DataGridViewRows 没有有用的字符串表示形式,更不用说在您感兴趣的列中显示值了。所以只显示了一些类型信息。

您需要使用单元格中的Value 来构建消息,大概是这样的:

var message = string.Join(Environment.NewLine, selectedRows["UserID"].Value.ToString());

【讨论】:

    猜你喜欢
    • 2016-08-02
    • 1970-01-01
    • 2018-08-08
    • 1970-01-01
    • 1970-01-01
    • 2021-04-28
    • 2019-10-13
    • 1970-01-01
    相关资源
    最近更新 更多