Deleting out of DataGrid

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

HawaiiDragonAsked:
Who is Participating?
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

Priest04Commented:
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
Anurag ThakurTechnical ManagerCommented:
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
HawaiiDragonAuthor Commented:
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
Cloud Class® Course: C++ 11 Fundamentals

This course will introduce you to C++ 11 and teach you about syntax fundamentals.

Priest04Commented:
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
HawaiiDragonAuthor Commented:
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
HawaiiDragonAuthor Commented:
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
Priest04Commented:
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

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
.NET Programming

From novice to tech pro — start learning today.

Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.