简体   繁体   English

更新和从DataGridView删除不起作用

[英]Update and Delete from DataGridView not functioning

I have a DataGridView which displays 3 rows, when I try to update my records it says successfully changed the records. 我有一个显示3行的DataGridView ,当我尝试更新记录时,它说成功更改了记录。 But when I check the database the records were not updated. 但是当我检查数据库时,记录没有更新。

And in the delete button it says I must select a record to delete but I already selected a row in my DataGridView 在删除按钮中,它说我必须选择要删除的记录,但是我已经在DataGridView选择了一行

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.Sql;
using System.Data.SqlClient;

namespace RFG_Inventory_and_Management_System
{
    public partial class AdminForm : Form
    {
        SqlCommand cmd;
        SqlConnection con = new SqlConnection(@"Data Source=.\SQLEXPRESS;AttachDbFilename=C:\Users\Acer\Documents\Visual Studio 2010\Projects\RFG Inventory and Management System\RFG Inventory and Management System\Database1.mdf;Integrated Security=True;User Instance=True");

        SqlCommandBuilder cmdbl;
        SqlDataAdapter adap;

        DataSet ds;
        int ID = 0;

        public AdminForm()
        {
            InitializeComponent();
            PayratesDisplay();
            NonMemberDisplay();
        }

        //Display Data in DataGridView  
        private void PayratesDisplay()
        {
            con.Open();
            DataTable dt = new DataTable();
            adap = new SqlDataAdapter("select * from tbl_payrates", con);
            adap.Fill(dt);
            dataGridView4.DataSource = dt;
            con.Close();
        }
        private void NonMemberDisplay()
        {
            con.Open();
            DataTable dt = new DataTable();
            adap = new SqlDataAdapter("SELECT tbl_nonMember.*, tbl_customer.lname, tbl_customer.fname, tbl_customer.mname, tbl_customer.gender, tbl_customer.age, tbl_customer.membership_type FROM    tbl_nonMember INNER JOIN tbl_customer ON tbl_nonMember.customerID = tbl_customer.customerID", con);
            adap.Fill(dt);
            dataGridView2.DataSource = dt;
            con.Close();
        }

        //Clear Data  
        private void ClearData()
        {
            tbMemship.Text = "";
            tbPerses.Text = "";
            tbDisc.Text = "";
            ID = 0;
        }  

        private void AdminForm_Load(object sender, EventArgs e)
        {

            // TODO: This line of code loads data into the 'database1DataSet.tbl_customer' table. You can move, or remove it, as needed.
            this.tbl_customerTableAdapter.Fill(this.database1DataSet.tbl_customer);
            // TODO: This line of code loads data into the 'database1DataSet.tbl_nonMember' table. You can move, or remove it, as needed.
            this.tbl_nonMemberTableAdapter.Fill(this.database1DataSet.tbl_nonMember);

        }

        private void fillByToolStripButton_Click(object sender, EventArgs e)
        {
            try
            {
                this.tbl_customerTableAdapter.FillBy(this.database1DataSet.tbl_customer);
            }
            catch (System.Exception ex)
            {
                System.Windows.Forms.MessageBox.Show(ex.Message);
            }
        }
        //----------------------------------BUTTONS FOR PAY RATE-------------------------------------------------------------//

        //dataGridView1 RowHeaderMouseClick Event  
        private void dataGridView4_RowHeaderMouseClick(object sender, DataGridViewCellMouseEventArgs e)
        {
            tbMemship.Text = dataGridView4.Rows[e.RowIndex].Cells[0].Value.ToString();
            tbPerses.Text = dataGridView4.Rows[e.RowIndex].Cells[1].Value.ToString();
            tbDisc.Text = dataGridView4.Rows[e.RowIndex].Cells[2].Value.ToString();
        }  

        private void btn_update_Click(object sender, EventArgs e)
        {
            if (tbMemship.Text != "" && tbPerses.Text != "" && tbDisc.Text != "")
            {
                cmd = new SqlCommand("update tbl_payrates set Membership=@Membership,PerSession=@PerSession where Discounted=@Discounted", con);
                con.Open();
                cmd.Parameters.AddWithValue("@Membership", tbMemship.Text);
                cmd.Parameters.AddWithValue("@PerSession", tbPerses.Text);
                cmd.Parameters.AddWithValue("@Discounted", tbDisc.Text);
                cmd.ExecuteNonQuery();
                MessageBox.Show("Record Updated Successfully");
                con.Close();
                PayratesDisplay();
                ClearData();
            }
            else
            {
                MessageBox.Show("Please Select Record to Update");
            } 
        }

        private void btn_PRadd_Click(object sender, EventArgs e)
        {
            DialogResult dr = MessageBox.Show("Are you sure to save Changes", "Message", MessageBoxButtons.YesNo, MessageBoxIcon.Information);
            if (dr == DialogResult.Yes)
            {
                con = new SqlConnection(@"Data Source=.\SQLEXPRESS;AttachDbFilename=C:\Users\Acer\Documents\Visual Studio 2010\Projects\RFG Inventory and Management System\RFG Inventory and Management System\Database1.mdf;Integrated Security=True;User Instance=True");
                con.Open();
                cmd = new SqlCommand("INSERT INTO tbl_payrates (Membership, PerSession, Discounted) VALUES (@Membership, @PerSession, @Discounted)", con);
                cmd.Parameters.AddWithValue("@Membership", tbMemship.Text);
                cmd.Parameters.AddWithValue("@PerSession", tbPerses.Text);
                cmd.Parameters.AddWithValue("@Discounted", tbDisc.Text);
                cmd.ExecuteNonQuery();
            }   
        }

        private void btn_PRdel_Click_1(object sender, EventArgs e)
        {
            //Update button update dataset after insertion,upadtion or deletion
            DialogResult dr = MessageBox.Show("Are you sure to save Changes", "Message", MessageBoxButtons.YesNo, MessageBoxIcon.Information);

            if (dr == DialogResult.Yes)
            {
                if (ID != 0)
                {
                    cmd = new SqlCommand("DELETE FROM tbl_payrates WHERE ID=@id", con);
                    con.Open();
                    cmd.Parameters.AddWithValue("@id", ID);
                    cmd.ExecuteNonQuery();
                    con.Close();
                    MessageBox.Show("Record Deleted Successfully!");
                    PayratesDisplay();
                    ClearData();
                }

                else
                {
                    MessageBox.Show("Please Select Record to Delete");
                }
            }
        }
    }
}

The whole AttachDbFileName= approach is flawed - at best! 整个AttachDbFileName =方法有缺陷-充其量! When running your app in Visual Studio, it will be copying around the .mdf file (from your App_Data directory to the output directory - typically .\\bin\\debug - where you app runs) and most likely , your INSERT works just fine - but you're just looking at the wrong .mdf file in the end! 在Visual Studio中运行应用程序时,它将在.mdf文件周围复制(从App_Data目录复制到输出目录-通常是.\\bin\\debug应用程序运行所在的位置),并且很可能 INSERT可以正常工作-但最后您只是看错了.mdf文件

If you want to stick with this approach, then try putting a breakpoint on the myConnection.Close() call - and then inspect the .mdf file with SQL Server Mgmt Studio Express - I'm almost certain your data is there. 如果您要坚持这种方法,请尝试在myConnection.Close()调用上放置一个断点,然后使用SQL Server Mgmt Studio Express检查.mdf文件-我几乎可以确定您的数据在那里。

The real solution in my opinion would be to 我认为真正的解决方案

  1. install SQL Server Express (and you've already done that anyway) 安装SQL Server Express(并且您已经完成了此操作)

  2. install SQL Server Management Studio Express 安装SQL Server Management Studio Express

  3. create your database in SSMS Express , give it a logical name (eg InventoryDb ) SSMS Express中创建数据库,并为其指定一个逻辑名称(例如InventoryDb

  4. connect to it using its logical database name (given when you create it on the server) - and don't mess around with physical database files and user instances. 使用其逻辑数据库名称 (在服务器上创建时提供)连接到该数据库 -并且不要弄乱物理数据库文件和用户实例。 In that case, your connection string would be something like: 在这种情况下,您的连接字符串将类似于:

     Data Source=.\\\\SQLEXPRESS;Database=InventoryDb;Integrated Security=True 

    and everything else is exactly the same as before... 和其他一切是完全一样的前...

Also see Aaron Bertrand's excellent blog post Bad habits to kick: using AttachDbFileName for more background info. 另请参阅亚伦·贝特朗(Aaron Bertrand)出色的博客文章不良习惯:使用AttachDbFileName获取更多背景信息。

i think you are not assigned the value to id .so id always 0 and you are not able to delete the record. 我认为您没有将值赋给id .so id始终为0,因此您无法删除记录。 try to assign the value to ID and delete.i hope it will work without any problem. 尝试将值分配给ID并删除。我希望它可以正常工作。

private void btn_PRdel_Click_1(object sender, EventArgs e)
    {
        //Update button update dataset after insertion,upadtion or deletion
        DialogResult dr = MessageBox.Show("Are you sure to save Changes", "Message", MessageBoxButtons.YesNo, MessageBoxIcon.Information);

        if (dr == DialogResult.Yes)
        {
            if (ID != 0)// where is the id value?
            {
                cmd = new SqlCommand("DELETE FROM tbl_payrates WHERE ID=@id", con);
                con.Open();
                cmd.Parameters.AddWithValue("@id", ID);
                cmd.ExecuteNonQuery();
                con.Close();
                MessageBox.Show("Record Deleted Successfully!");
                PayratesDisplay();
                ClearData();
            }

            else
            {
                MessageBox.Show("Please Select Record to Delete");
            }
        }
    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM