【问题标题】:Issue deleting from DGV and Database at same time同时从 DGV 和数据库中删除问题
【发布时间】:2014-04-09 18:56:51
【问题描述】:

我有一个使用 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);
        }







    }      
}

}

【问题讨论】:

    标签: c# sql datagridview


    【解决方案1】:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-05-04
      • 1970-01-01
      • 2012-04-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多