我去过网站上的很多其他主题,但似乎无法让这个东西发挥作用。我正在创建一个库存数据库程序来跟踪我的枪支。我有一个表单 (AmmunitionForm.cs),其中包含 DataGridView (ammoDGV) 和删除按钮。我可以将其从网格中删除,但我似乎无法让更改影响数据库。这是我对这个主题的知识的边缘,请记住这一点。这是我当前拥有的代码(注意删除按钮方法):
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Data.SqlClient;
using System.Data.Sql;
namespace Firearm_Asset_Management_Database
{
public partial class AmmunitionForm : Form
{
public AmmunitionForm()
{
InitializeComponent();
}
private void AmmunitionForm_Load(object sender, EventArgs e)
{
// TODO: This line of code loads data into the 'fAMDatabaseDataSet.AmmunitionTable' table. You can move, or remove it, as needed.
this.ammunitionTableTableAdapter.Fill(this.fAMDatabaseDataSet.AmmunitionTable);
}
private void addAmmoButton_Click(object sender, EventArgs e)
{
NewAmmunition newAmmunition = new NewAmmunition();
newAmmunition.Show();
}
private void refreshButton_Click(object sender, EventArgs e)
{
SqlConnection con = new SqlConnection(@"Data Source=.\SQLEXPRESS;AttachDbFilename=c:\users\brmcbrid\documents\visual studio 2010\Projects\Firearm Asset Management Database\Firearm Asset Management Database\FAMDatabase.mdf;Integrated Security=True;User Instance=True");
string query = "select * from AmmunitionTable";
SqlCommand cmd = new SqlCommand(query, con);
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataTable dt = new DataTable();
da.Fill(dt);
ammoDGV.DataSource = dt;
}
private void closeButton_Click(object sender, EventArgs e)
{
this.Close();
}
private void deleteButton_Click(object sender, EventArgs e)
{
SqlConnection con = new SqlConnection(@"Data Source=.\SQLEXPRESS;AttachDbFilename=c:\users\brmcbrid\documents\visual studio 2010\Projects\Firearm Asset Management Database\Firearm Asset Management Database\FAMDatabase.mdf;Integrated Security=True;User Instance=True");
SqlCommand cmd = new SqlCommand();
if (ammoDGV.Rows.Count > 1 && ammoDGV.SelectedRows[0].Index != ammoDGV.Rows.Count - 1)
{
cmd.CommandText = "DELETE FROM AmmunitionTable WHERE Caliber=" + ammoDGV.SelectedRows[0].Cells[0].Value.ToString() + "";
con.Open();
cmd.Connection = con;
cmd.ExecuteNonQuery();
con.Close();
ammoDGV.Rows.RemoveAt(ammoDGV.SelectedRows[0].Index);
MessageBox.Show("Row has been Deleted");
}
}
}
}
任何帮助将不胜感激!
最佳答案
您的第一栏中到底是什么?这是我认为的口径。它在数据库中保存为整数吗?如果没有,您应该在 SQL 命令中插入单个配额,如下所示:
"DELETE FROM AmmunitionTable WHERE Caliber='" + ammoDGV.SelectedRows[0].Cells[0].Value.ToString() + "'";
关于c# - 从datagridview中删除数据库,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24744054/