从 datagridview 中删除选定的行

Delete selected rows from datagridview

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

                    }
                }
            }
        }

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

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

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