Click here to Skip to main content
15,882,113 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
The problem is whenever I update any record, it gets updated in database. But in gridview it adds another record instead of updating the existing one. Same problem with delete operation, record gets deleted from database but not from gridview.

I have searched it already but didn't found proper solution.

Here is the code :
(The method setGroupGridView is called after each operation i.e. insert,update,delete
& the code is error free just need to add some lines for gridview updation.)

Main Form
C#
public partial class frmMain : Form
    {
        Connection cn = new Connection();
        int GId,MId,STId,LId,LTId;
        DataSet ds = new DataSet();
        DataTable dt;

        public frmMain()
        {
            InitializeComponent();
        }

        public frmMain(Form frm)
        {
            InitializeComponent();
        }

        private void frmMain_Load(object sender, EventArgs e)
        {
            
            setGroupGridView();

            GId = cn.AutoCodeGen("tblGroupDetails");
            lblGId.Text = GId.ToString();

            //MId = cn.AutoCodeGen("tblMemberDetails");
            //lblMemberId.Text = MId.ToString();


        }

        # region Group Details Code
        //code for inserting record on button click
        private void btnGAdd_Click(object sender, EventArgs e)
        {
            GroupDetails gd=new GroupDetails(lblGId.Text,txtGName.Text);
            gd.Add();
            setGroupGridView();
            resetGroupDetails();
        }
        
        //code for updating record on button click
        private void btnGUpdate_Click(object sender, EventArgs e)
        {
             GroupDetails gd = new GroupDetails(lblGId.Text, txtGName.Text);
             gd.Update();
             setGroupGridView();
             resetGroupDetails();
             btnGUpdate.Enabled = false;
        }

        private void dgvGroupDetails_CellContentClick(object sender, DataGridViewCellEventArgs e)
        {
            if (e.ColumnIndex == 0) //code for setting values in controls on clicking edit image in gridview
            {
                btnGUpdate.Enabled = true;
                lblGId.Text = dgvGroupDetails.Rows[e.RowIndex].Cells[2].Value.ToString();
                txtGName.Text = dgvGroupDetails.Rows[e.RowIndex].Cells[3].Value.ToString();
            }
            else if (e.ColumnIndex == 1)  //code for deleting record on clicking delete image in gridview
            {
                GroupDetails gd = new GroupDetails(dgvGroupDetails.Rows[e.RowIndex].Cells[2].Value.ToString(), dgvGroupDetails.Rows[e.RowIndex].Cells[3].Value.ToString());
                gd.Delete();
                cn.da.Update(dt);
                setGroupGridView();
                resetGroupDetails();
            }
        }

        private void resetGroupDetails()
        {
            GId = cn.AutoCodeGen("tblGroupDetails");
            lblGId.Text = GId.ToString();
            txtGName.Text = "";
        }

        //Binding DataGridview
        private void setGroupGridView()
        {
            
            dt = new DataTable();
            dt = cn.GetDetails("select * from tblGroupDetails");
            dgvGroupDetails.DataSource = dt;
            dgvGroupDetails.ForeColor = Color.Black;
            for (int i = 2; i < dgvGroupDetails.Columns.Count; i++)
            {
                dgvGroupDetails.Columns[i].Width = 150;
            }
        }
        #endregion

    }


Class for insert, update & delete:
C#
class GroupDetails
   {
       protected int GId;
       protected string GName;
       Connection con;

       public GroupDetails(string _GId, string _GName)
       {
           con = new Connection();
           GId = Convert.ToInt16(_GId);
           GName = _GName;
       }

       public void Add()
       {
           con.Execute("insert into tblGroupDetails(GId,GName) values("+ GId +",'"+ GName +"')");
       }

       public void Update()
       {
           con.Execute("update tblGroupDetails set GName='"+ GName +"' where GId=" + GId +"");
       }

       public void Delete()
       {
           con.Execute("delete from tblGroupDetails where GId=" + GId + "");
       }
   }


Class for connection to db:

C#
 public class Connection
    {
        public SqlConnection con;
        public SqlCommand cmd = new SqlCommand();
        public SqlDataAdapter da;
        public DataSet ds = new DataSet();
        public DataTable dt = new DataTable();
        int code;

        public Connection()
        {
            try
            {
                con = new SqlConnection("Data Source=abc;Initial Catalog=db;Integrated Security=True;Pooling=False");
                con.Open();
            }
            catch (Exception e)
            {
                MessageBox.Show(e.Message, "Connection Failed");
            }
        }

        public void Execute(string query)
        {
            try
            {
                cmd.CommandText = query;
                cmd.Connection = con;
                cmd.ExecuteNonQuery();
            }
            catch (Exception e)
            {
                MessageBox.Show(e.Message, "Operation Failed.");
            }

        }

        public DataTable GetDetails(string query)
        {
            try
            {
                cmd.CommandText = query;
                cmd.Connection = con;
                da = new SqlDataAdapter(cmd);
                da.Fill(dt);
                return dt;
            }
            catch (Exception e)
            {
                MessageBox.Show(e.Message, "Operation Failed.");
                return null;
            }
        }
}


For solution I have already tried following code, But works none for me :

//1st solution
dgvGroupDetails.Rows.Clear();

// 2nd solution
If(dgvGroupDetails.DataSource != null)
{
    dgvGroupDetails.DataSource=null;
}
else
{
    dgvGroupDetails.Rows.Clear();
}
Posted
Updated 26-Jun-14 9:56am
v4
Comments
Jafarinejadvazifehkhorani 26-Jun-14 12:30pm    
please provide the code in the case that you want us to help you.and there is a good example here
http://www.asp.net/web-forms/tutorials/data-access/accessing-the-database-directly-from-an-aspnet-page/inserting-updating-and-deleting-data-with-the-sqldatasource-cs
Sneha_10 26-Jun-14 13:37pm    
Que updated with code.......check out if you can help me.....
Sneha_10 26-Jun-14 13:45pm    
And thank you for the link but if is for web app...not for windows app.....
Jafarinejadvazifehkhorani 26-Jun-14 17:32pm    
answer is updated
Sneha_10 27-Jun-14 5:25am    
Thank you for this solution.....It works..... :)

just add
dt = new DataTable();
to GetDetails method in Connection class.
and it should be look like this :

SQL
public DataTable GetDetails(string query)
       {
           try
           {
               dt = new DataTable();
               cmd.CommandText = query;
               cmd.Connection = con;
               da = new SqlDataAdapter(cmd);
               da.Fill(dt);
               return dt;
           }
           catch (Exception e)
           {
               MessageBox.Show(e.Message, "Operation Failed.");
               return null;
           }
       }



the issue is in SetGroupGridView method you are creating new dataTable but the returend Data table is another object. basically datatable is refrence type :) and you could change the follwoing method
C#
private void SetGroupGridView()
       {

           dt = new DataTable();
           dt = cn.GetDetails("select * from tbl1");
           dgvGroupDetails.DataSource = dt;
           dgvGroupDetails.ForeColor = Color.Black;
           for (int i = 2; i < dgvGroupDetails.Columns.Count; i++)
           {
               dgvGroupDetails.Columns[i].Width = 150;
           }
       }


to

C#
private void SetGroupGridView()
{
    dgvGroupDetails.DataSource = cn.GetDetails("select * from tbl1"); ;
    dgvGroupDetails.ForeColor = Color.Black;
    for (int i = 2; i < dgvGroupDetails.Columns.Count; i++)
    {
        dgvGroupDetails.Columns[i].Width = 150;
    }
}
 
Share this answer
 
I had a similar problem before.

I will not assure you this is the best solution, but consider using this to refresh your grid with the correct data.
just use this one:
C#
InitializeComponent();
 
Share this answer
 
Comments
Sneha_10 27-Jun-14 5:26am    
Thank you for your solution.....But Solution 2 has worked for me.....

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900