c# - 行未在数据网格 C# 中删除
问题描述
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);
}
解决方案
像这样试试。
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
推荐阅读
- php - 我帐户中的 Woocommerce 订单查看页面显示 404 未找到
- flutter - 我在图像上添加了 Watermaek,但图像未加载
- typescript - 在 Vue 打字稿中使用 i18n
- image-manipulation - CodeIgniter 4 图像处理错误 withFile() null
- eloquent - Eloquent 如何使用 (NOT) EXISTS 和选择子查询
- at-command - GSM/GPRS 板 sim800c "AT+CTTS=?" 返回“错误”
- python - 具有多个输入的 TensorFlow 生成器读取多个文件会导致内核崩溃
- python - Python 套接字模块未检测到 TFTP RRQ
- python - Amazon Neptune 中批量加载的 CSV 数据格式
- azure - 在 AutoMLConfig (azureml) 中使用“cv_splits_indices”