简体   繁体   中英

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. 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

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! 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!

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.

The real solution in my opinion would be to

  1. install SQL Server Express (and you've already done that anyway)

  2. install SQL Server Management Studio Express

  3. create your database in SSMS Express , give it a logical name (eg 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.

i think you are not assigned the value to id .so id always 0 and you are not able to delete the record. try to assign the value to ID and delete.i hope it will work without any problem.

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");
            }
        }
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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