同时从DGV和数据库中删除问题

时间:2014-04-09 18:56:52

标签: c# sql datagridview

我有一个使用Windows窗体的程序。这是一个库存程序,可以让我跟踪各种商品的库存。我在主页面上显示了一个DataGridView以及一个删除按钮。当我选择行并单击按钮时,它将从DataGridView中删除该条目。当我刷新条目返回。我非常肯定在删除按钮单击我需要与表建立连接...尝试了几种方法来做它但我似乎错过了一些东西,因为它只是无法正常工作。有任何想法吗? Button2_Click是删除功能。

DGV的主要表格:

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;
using Microsoft.Win32;
using System.Threading;


namespace WindowsFormsApplication2
{
public partial class Main : Form
{        
    public Main()
    {

        InitializeComponent();

    }

    private void Main_Load(object sender, EventArgs e)
    {

        // TODO: This line of code loads data into the 'userLoginDataSet.WeaponData' table. You can move, or remove it, as needed.
        this.weaponDataTableAdapter.Fill(this.userLoginDataSet.WeaponData);

    }

    private void button1_Click(object sender, EventArgs e)
    {

        AddWeapon aw = new AddWeapon(); // pass this, the main form
        aw.Show();

    }

    private void button3_Click(object sender, EventArgs e)
    {

        //Refresh weaponList DataGridView to show latest updates.
        SqlConnection con = new SqlConnection(@"Data Source=.\SQLEXPRESS;AttachDbFilename=C:\Users\brmcbrid\Documents\Visual Studio 2010\Projects\WindowsFormsApplication2\WindowsFormsApplication2\UserLogin.mdf;Integrated Security=True;Connect Timeout=30;User Instance=True");
        string query = "select * from WeaponData";
        SqlCommand cmd = new SqlCommand(query, con);
        SqlDataAdapter da = new SqlDataAdapter(cmd);
        DataTable dt = new DataTable();
        da.Fill(dt);
        weaponList.DataSource = dt;

    }

    private void checkedListBox1_SelectedIndexChanged(object sender, EventArgs e)
    {

    }



    private void exitToolStripMenuItem_Click(object sender, EventArgs e)
    {
        Close();
    }

    private void button2_Click(object sender, EventArgs e)
    {
        foreach (DataGridViewRow item in this.weaponList.SelectedRows)
        {
            weaponList.Rows.RemoveAt(item.Index);
        }







    }      
}

}

1 个答案:

答案 0 :(得分:1)

您应该从绑定到datagridview的数据表中删除记录... datagridview将自动反映更改