从datagridview中删除选定的行

时间:2015-03-03 19:31:51

标签: c# checkbox datagridview

如果在该行中选中了checkboxcolumn按钮,我将创建一个列表来添加第一列中的项目。当弹出消息框询问我是否确定要删除时,它显示的值是" 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);
                        }

                    }
                }
            }
        }

1 个答案:

答案 0 :(得分:0)

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

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

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