行未在数据网格 C# 中删除
Posted
技术标签:
【中文标题】行未在数据网格 C# 中删除【英文标题】:Row not deleting in datagrid C# 【发布时间】:2021-05-23 19:42:32 【问题描述】:在选择DataGridView
并按下删除按钮后,我想从我的DataGridView
中删除一行。如果我有一个 id 或 int
作为第一列输入,它确实有效。但现在我有一个nvarchar
类型一。那么我该如何解决获取input string is not in correct format
的问题。这是我的代码
// No row selected no delete....
if (dataGridView1.SelectedRows.Count == 0)
return; // show a message here to inform
// Prepare the command text with the parameter placeholder
string sql = "DELETE FROM cabphase3 WHERE driver_name = @rowID";
// Create the connection and the command inside a using block
using (SqlConnection myConnection = new SqlConnection(@"Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=C:\Users\mrdar\source\repos\HTC\HTC\Database1.mdf;Integrated Security=True"))
using (SqlCommand deleteRecord = new SqlCommand(sql, myConnection))
myConnection.Open();
int selectedIndex = dataGridView1.SelectedRows[0].Index;
// gets the RowID from the first column in the grid
int rowID = Convert.ToInt32(dataGridView1[0, selectedIndex].Value);
// Add the parameter to the command collection
deleteRecord.Parameters.Add("@rowID", SqlDbType.Int).Value = rowID;
deleteRecord.ExecuteNonQuery();
// Remove the row from the grid
dataGridView1.Rows.RemoveAt(selectedIndex);
【问题讨论】:
评估“我有一个 nvarchar 类型”和“int rowID = Convert.ToInt32(dataGridView1[0, selectedIndex].Value);”,然后开始思考可能出了什么问题... @Luuk 应该用什么代替 ToInt32 我希望你知道这行代码的作用:Convert.ToInt32(dataGridView1[0, selectedIndex].Value);
如果你知道这一点,那么你现在也想现在做一些不同的事情。
@HaramHoe 检查dataGridView1[0, selectedIndex].Value
的值。你会找到根本原因
【参考方案1】:
这样试试吧。
using System;
using System.Data;
using System.Drawing;
using System.Windows.Forms;
namespace WindowsFormsApplication1
public partial class Form1 : Form
private int rowIndex = 0;
public Form1()
InitializeComponent();
private void Form1_Load(object sender, EventArgs e)
DataTable dt = new DataTable();
dt.Columns.Add("Id", typeof(int));
dt.Columns.Add("Publisher Name", typeof(string));
dt.Columns.Add("Book", typeof(string));
for (int i = 1; i < 11; i++)
dt.Rows.Add(i, "PubName" + i, "Book"+i);
dataGridView1.DataSource = dt;
this.dataGridView1.RowsDefaultCellStyle.BackColor = Color.Bisque;
this.dataGridView1.AlternatingRowsDefaultCellStyle.BackColor = Color.Beige;
private void dataGridView1_CellMouseUp(object sender, DataGridViewCellMouseEventArgs e)
if (e.Button == MouseButtons.Right)
this.dataGridView1.Rows[e.RowIndex].Selected = true;
this.rowIndex = e.RowIndex;
this.dataGridView1.CurrentCell = this.dataGridView1.Rows[e.RowIndex].Cells[1];
this.contextMenuStrip1.Show(this.dataGridView1, e.Location);
contextMenuStrip1.Show(Cursor.Position);
private void contextMenuStrip1_Click(object sender, EventArgs e)
if (!this.dataGridView1.Rows[this.rowIndex].IsNewRow)
this.dataGridView1.Rows.RemoveAt(this.rowIndex);
http://csharp.net-informations.com/datagridview/deletegridview.htm
【讨论】:
以上是关于行未在数据网格 C# 中删除的主要内容,如果未能解决你的问题,请参考以下文章