Solved

Deleting out of DataGrid

Posted on 2008-10-17
7
365 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
Comment Utility
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
Comment Utility
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
Comment Utility
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
How your wiki can always stay up-to-date

Quip doubles as a “living” wiki and a project management tool that evolves with your organization. As you finish projects in Quip, the work remains, easily accessible to all team members, new and old.
- Increase transparency
- Onboard new hires faster
- Access from mobile/offline

 
LVL 18

Expert Comment

by:Priest04
Comment Utility
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
Comment Utility
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
Comment Utility
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
Comment Utility
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

IT, Stop Being Called Into Every Meeting

Highfive is so simple that setting up every meeting room takes just minutes and every employee will be able to start or join a call from any room with ease. Never be called into a meeting just to get it started again. This is how video conferencing should work!

Join & Write a Comment

More often than not, we developers are confronted with a need: a need to make some kind of magic happen via code. Whether it is for a client, for the boss, or for our own personal projects, the need must be satisfied. Most of the time, the Framework…
Real-time is more about the business, not the technology. In day-to-day life, to make real-time decisions like buying or investing, business needs the latest information(e.g. Gold Rate/Stock Rate). Unlike traditional days, you need not wait for a fe…
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…
This tutorial demonstrates a quick way of adding group price to multiple Magento products.

762 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