Solved

Deleting out of DataGrid

Posted on 2008-10-17
7
383 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
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 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
Certified OpenStack Administrator Course

We just refreshed our COA course based on the Newton exam.  With 14 labs, this course goes over the different OpenStack services that are part of the certification: Dashboard, Identity Service, Image Service, Networking, Compute, Object Storage, Block Storage, and Orchestration.

 
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

On Demand Webinar: Networking for the Cloud Era

Did you know SD-WANs can improve network connectivity? Check out this webinar to learn how an SD-WAN simplified, one-click tool can help you migrate and manage data in the cloud.

Question has a verified solution.

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

Many of us here at EE write code. Many of us write exceptional code; just as many of us write exception-prone code. As we all should know, exceptions are a mechanism for handling errors which are typically out of our control. From database errors, t…
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…
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…
Michael from AdRem Software outlines event notifications and Automatic Corrective Actions in network monitoring. Automatic Corrective Actions are scripts, which can automatically run upon discovery of a certain undesirable condition in your network.…

617 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