Solved

Deleting out of DataGrid

Posted on 2008-10-17
7
366 Views
Last Modified: 2013-12-17
I am trying to delet rows out of a data grid programaticaly using a stored procedure and on a button click.
Here is my code... anyone got any ideas? Also after the record is deleted how do I get it to refresh?
private void btnDelete_Click(object sender, EventArgs e)

        {

            //Inside a try

            try

            {

                SqlParameter[] test = new SqlParameter[3];

                test[0] = new SqlParameter("@Name", dataGridView1.SelectedRows[0].ToString());

                test[1] = new SqlParameter("@Phone", dataGridView1.SelectedRows[1].ToString());

                test[2] = new SqlParameter("@Birthday", dataGridView1.SelectedRows[2].ToString());
 

                SqlConnection scs = new SqlConnection();
 

                string DropInfo = ConfigurationManager.ConnectionStrings["Phone_number_birthday.Properties.Settings.BirthdaysConnectionString"].ToString();

                scs.ConnectionString = DropInfo;
 

                SqlCommand cmd = new SqlCommand();

                //cmd.Connection = scs.ConnectionString;

                cmd.CommandType = CommandType.StoredProcedure;

                cmd.CommandText = "NewDeleteCommand";

                cmd.Parameters.AddRange(test);

                cmd.Connection = scs;

                cmd.Connection.Open();

                int one = cmd.ExecuteNonQuery();

                cmd.Connection.Close();
 

                if (one > -1)

                {

                    MessageBox.Show("Database Updated");

                    this.Close();

                    PhoneListForm.ActiveForm.Refresh();

                }

                else

                {

                }

            }

            //Close connection in finally

            //Catch problems

            //sql command object

            //command type

            //DataAccess

            //Using AppConfig ConnectionString (pull from)

            //Params

            //ExecuteNonQuery

            catch (Exception ex)

            {

                ex.ToString();

            }

           // this.Close();

            this.Refresh();

        }

Open in new window

0
Comment
Question by:HawaiiDragon
  • 3
  • 3
7 Comments
 
LVL 18

Expert Comment

by:Priest04
ID: 22744225
If DataGridView is not bound, then after you have executed sp, you will need to remove the row manually.

dg.Rows.Remove(dg.CurrectRow);

if DataGridView is bound to a datasource (ex datatable), then remove the row either from datatable (or datagridview), and then call Update method on the dataadapter. If it is bound, then if you remove it from datatable, you dont need to remove it from datagridview, it will remove it automatically.


Goran
0
 
LVL 26

Expert Comment

by:Anurag Thakur
ID: 22747532
When you do the db update bring back the fresh set of data and bind it again to the data grid view
it will be the simplest of solutions
0
 

Author Comment

by:HawaiiDragon
ID: 22758121
this is what ive done.
   private void btnDelete_Click(object sender, EventArgs e)

        {

            

            //Inside a try

            try

            {

                SqlParameter[] test = new SqlParameter[3];

                test[0] = new SqlParameter("@Name", dataGridView1.Rows[dataGridView1.CurrentCell.RowIndex].Cells[0].Value);

                test[1] = new SqlParameter("@Phone", dataGridView1.Rows[dataGridView1.CurrentCell.RowIndex].Cells[1].Value);

                test[2] = new SqlParameter("@Birthday", dataGridView1.Rows[dataGridView1.CurrentCell.RowIndex].Cells[2].Value);
 

                SqlConnection scs = new SqlConnection();
 

                string DropInfo = ConfigurationManager.ConnectionStrings["Phone_number_birthday.Properties.Settings.BirthdaysConnectionString"].ToString();

                scs.ConnectionString = DropInfo;
 

                SqlCommand cmd = new SqlCommand();

                //cmd.Connection = scs.ConnectionString;

                cmd.CommandType = CommandType.StoredProcedure;

                cmd.CommandText = "NewDeleteCommand";

                cmd.Parameters.AddRange(test);

                cmd.Connection = scs;

                cmd.Connection.Open();

                int one = cmd.ExecuteNonQuery();

                cmd.Connection.Close();
 

                if (one > -1)

                {

                    MessageBox.Show("Database Updated");
 

                    refilltabel();
 

                }

                else

                {

                }

            }

            //Close connection in finally

            //Catch problems

            //sql command object

            //command type

            //DataAccess

            //Using AppConfig ConnectionString (pull from)

            //Params

            //ExecuteNonQuery

            catch (Exception ex)

            {

                ex.ToString();

            }

           // this.Close();

            this.Refresh();

        }

Open in new window

0
3 Use Cases for Connected Systems

Our Dev teams are like yours. They’re continually cranking out code for new features/bugs fixes, testing, deploying, testing some more, responding to production monitoring events and more. It’s complex. So, we thought you’d like to see what’s working for us.

 
LVL 18

Expert Comment

by:Priest04
ID: 22758521
If it deeltes only one record from database, then yhis is what you should do in the end


cmd.Connection.Open();

int one = cmd.ExecuteNonQuery();

cmd.Connection.Close();

 

if (one == 1) // only one record should be deleted, otherwise we have a problem

{

    MessageBox.Show("Database Updated");

 

    dataGridView1.Rows.Remove(dg.CurrentRow); // remove it manually, no need to retrieve data from database

 

}

else

{

}

Open in new window

0
 

Author Comment

by:HawaiiDragon
ID: 22759265
Okay if I put that code in it wont delete at all. I am including my entrie code for the page.
I just need the record to drop off the database and then not show up in the data set... this one is killing me.
using System;

using System.Collections.Generic;

using System.ComponentModel;

using System.Data;

using System.Drawing;

using System.Text;

using System.Windows.Forms;

using System.Data.SqlClient;

using System.Configuration;

using System.Web;
 

namespace Phone_number_birthday

{

    public partial class PhoneListForm : Form

    {

        public PhoneListForm()

        {

            InitializeComponent();

           

        }

        public void Refresher()

        {

            this.Refresh();

        }
 

        private void btnAdd_Click(object sender, EventArgs e)

        {

            NewDataForm objnewdataform = new NewDataForm();

            objnewdataform.ShowDialog();

            this.tbl_BdayTableAdapter.Fill(this.birthdaysDataSet2.tbl_Bday);

            this.Refresh();
 

      

        }
 

        private void PhoneListForm_Load(object sender, EventArgs e)

        {

            // TODO: This line of code loads data into the 'birthdaysDataSet2.tbl_Bday' table. You can move, or remove it, as needed.

            this.tbl_BdayTableAdapter.Fill(this.birthdaysDataSet2.tbl_Bday);

            // TODO: This line of code loads data into the 'birthdaysDataSet.tbl_Bday' table. You can move, or remove it, as needed.

          //  this.tbl_BdayTableAdapter.Fill(this.birthdaysDataSet.tbl_Bday);

            // TODO: This line of code loads data into the 'birthdaysDataSet.tbl_Bday' table. You can move, or remove it, as needed.

            //this.tbl_BdayTableAdapter.Fill(this.birthdaysDataSet.tbl_Bday);

            this.Refresh();

        }
 

        private void fillByToolStripButton_Click(object sender, EventArgs e)

        {

            try

            {

                this.tbl_BdayTableAdapter.FillBy(this.birthdaysDataSet2.tbl_Bday);

            }

            catch (System.Exception ex)

            {

                System.Windows.Forms.MessageBox.Show(ex.Message);

            }
 

        }
 

        public void refilltabel()

        {

            this.tbl_BdayTableAdapter.Fill(this.birthdaysDataSet2.tbl_Bday);

            dataGridView1.DataSource = birthdaysDataSet2.tbl_Bday;

        

            this.dataGridView1.Update();

            this.dataGridView1.Refresh();

        }

        private void btnDelete_Click(object sender, EventArgs e)

        {

            

            //Inside a try

            try

            {

                SqlParameter[] test = new SqlParameter[3];

                test[0] = new SqlParameter("@Name", dataGridView1.Rows[dataGridView1.CurrentCell.RowIndex].Cells[0].Value);

                test[1] = new SqlParameter("@Phone", dataGridView1.Rows[dataGridView1.CurrentCell.RowIndex].Cells[1].Value);

                test[2] = new SqlParameter("@Birthday", dataGridView1.Rows[dataGridView1.CurrentCell.RowIndex].Cells[2].Value);
 

                SqlConnection scs = new SqlConnection();
 

                string DropInfo = ConfigurationManager.ConnectionStrings["Phone_number_birthday.Properties.Settings.BirthdaysConnectionString"].ToString();

                scs.ConnectionString = DropInfo;
 

                SqlCommand cmd = new SqlCommand();

                //cmd.Connection = scs.ConnectionString;

                cmd.CommandType = CommandType.StoredProcedure;

                cmd.CommandText = "NewDeleteCommand";

                cmd.Parameters.AddRange(test);

                cmd.Connection = scs;

                cmd.Connection.Open();

                int one = cmd.ExecuteNonQuery();

                cmd.Connection.Close();
 
 
 
 
 
 

                if (one > -1)

                {

                    MessageBox.Show("Database Updated");
 

                    refilltabel();
 

                }

                else

                {

                }

            }

            //Close connection in finally

            //Catch problems

            //sql command object

            //command type

            //DataAccess

            //Using AppConfig ConnectionString (pull from)

            //Params

            //ExecuteNonQuery

            catch (Exception ex)

            {

                ex.ToString();

            }

           // this.Close();

            this.Refresh();

        }
 

        private void btnRefresh_Click(object sender, EventArgs e)

        {

            //does not work

          //  DataGridView dataGridView1 = new DataGridView();

          //  dataGridView1.Refresh();

        }
 

        //private void btnAdd_Click(object sender, EventArgs e)

        //{

        //    Form.ActiveForm = NewDataForm;

        //   // Application.Run(new NewDataForm());

        //}

    }

}

Open in new window

0
 

Author Comment

by:HawaiiDragon
ID: 22759324
continued from top
    

        }
 

        private void PhoneListForm_Load(object sender, EventArgs e)

        {

            // TODO: This line of code loads data into the 'birthdaysDataSet2.tbl_Bday' table. You can move, or remove it, as needed.

            this.tbl_BdayTableAdapter.Fill(this.birthdaysDataSet2.tbl_Bday);

            // TODO: This line of code loads data into the 'birthdaysDataSet.tbl_Bday' table. You can move, or remove it, as needed.

          //  this.tbl_BdayTableAdapter.Fill(this.birthdaysDataSet.tbl_Bday);

            // TODO: This line of code loads data into the 'birthdaysDataSet.tbl_Bday' table. You can move, or remove it, as needed.

            //this.tbl_BdayTableAdapter.Fill(this.birthdaysDataSet.tbl_Bday);

            this.Refresh();

        }
 

        private void fillByToolStripButton_Click(object sender, EventArgs e)

        {

            try

            {

                this.tbl_BdayTableAdapter.FillBy(this.birthdaysDataSet2.tbl_Bday);

            }

            catch (System.Exception ex)

            {

                System.Windows.Forms.MessageBox.Show(ex.Message);

            }
 

        }
 

        public void refilltabel()

        {

            this.tbl_BdayTableAdapter.Fill(this.birthdaysDataSet2.tbl_Bday);

            dataGridView1.DataSource = birthdaysDataSet2.tbl_Bday;

        

            this.dataGridView1.Update();

            this.dataGridView1.Refresh();

        }

        private void btnDelete_Click(object sender, EventArgs e)

        {

            

            //Inside a try

            try

            {

                SqlParameter[] test = new SqlParameter[3];

                test[0] = new SqlParameter("@Name", dataGridView1.Rows[dataGridView1.CurrentCell.RowIndex].Cells[0].Value);

                test[1] = new SqlParameter("@Phone", dataGridView1.Rows[dataGridView1.CurrentCell.RowIndex].Cells[1].Value);

                test[2] = new SqlParameter("@Birthday", dataGridView1.Rows[dataGridView1.CurrentCell.RowIndex].Cells[2].Value);
 

                SqlConnection scs = new SqlConnection();
 

                string DropInfo = ConfigurationManager.ConnectionStrings["Phone_number_birthday.Properties.Settings.BirthdaysConnectionString"].ToString();

                scs.ConnectionString = DropInfo;
 

                SqlCommand cmd = new SqlCommand();

                //cmd.Connection = scs.ConnectionString;

                cmd.CommandType = CommandType.StoredProcedure;

                cmd.CommandText = "NewDeleteCommand";

                cmd.Parameters.AddRange(test);

                cmd.Connection = scs;

                cmd.Connection.Open();

                int one = cmd.ExecuteNonQuery();

                cmd.Connection.Close();
 
 
 
 
 
 

                if (one > -1)

                {

                    MessageBox.Show("Database Updated");
 

                    refilltabel();
 

                }

                else

                {

                }

            }

            //Close connection in finally

            //Catch problems

            //sql command object

            //command type

            //DataAccess

            //Using AppConfig ConnectionString (pull from)

            //Params

            //ExecuteNonQuery

            catch (Exception ex)

            {

                ex.ToString();

            }

           // this.Close();

            this.Refresh();

        }
 

        private void btnRefresh_Click(object sender, EventArgs e)

        {

            //does not work

          //  DataGridView dataGridView1 = new DataGridView();

          //  dataGridView1.Refresh();

        }
 

        //private void btnAdd_Click(object sender, EventArgs e)

        //{

        //    Form.ActiveForm = NewDataForm;

        //   // Application.Run(new NewDataForm());

        //}

    }

}

Open in new window

0
 
LVL 18

Accepted Solution

by:
Priest04 earned 500 total points
ID: 22759410
If record is not deleted fromdatabase, then this means that it didnt find the row to delete - WHERE clause returned 0 rows..

Check the values of the paramteres you are passing - put a breakpoint on this line

SqlParameter[] test = new SqlParameter[3];

and walkthrough the lines and see the values of parameres. Then run manually stored procedure with this values and see if it will delete any records.

Btw, the concept you are using here is really not the best one, but since you are just starting to program, then its good to move through all the "phases". :)

Just remember one thing, try to take trips to database as less as possible, meaining if you delete some row with a SQL query, just remove the record from the datagridview (or some collection), dont reload data again. Its very ineffective if you need to load, for example,  3,000 records just because you have delete one.
0

Featured Post

3 Use Cases for Connected Systems

Our Dev teams are like yours. They’re continually cranking out code for new features/bugs fixes, testing, deploying, testing some more, responding to production monitoring events and more. It’s complex. So, we thought you’d like to see what’s working for us.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

In my previous two articles we discussed Binary Serialization (http://www.experts-exchange.com/A_4362.html) and XML Serialization (http://www.experts-exchange.com/A_4425.html). In this article we will try to know more about SOAP (Simple Object Acces…
Today I had a very interesting conundrum that had to get solved quickly. Needless to say, it wasn't resolved quickly because when we needed it we were very rushed, but as soon as the conference call was over and I took a step back I saw the correct …
This is Part 3 in a 3-part series on Experts Exchange to discuss error handling in VBA code written for Excel. Part 1 of this series discussed basic error handling code using VBA. http://www.experts-exchange.com/videos/1478/Excel-Error-Handlin…
Internet Business Fax to Email Made Easy - With  eFax Corporate (http://www.enterprise.efax.com), you'll receive a dedicated online fax number, which is used the same way as a typical analog fax number. You'll receive secure faxes in your email, f…

895 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

12 Experts available now in Live!

Get 1:1 Help Now