Go Premium for a chance to win a PS4. Enter to Win

x
  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 386
  • Last Modified:

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

0
HawaiiDragon
Asked:
HawaiiDragon
  • 3
  • 3
1 Solution
 
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 ThakurCommented:
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
NFR key for Veeam Backup for Microsoft Office 365

Veeam is happy to provide a free NFR license (for 1 year, up to 10 users). This license allows for the non‑production use of Veeam Backup for Microsoft Office 365 in your home lab without any feature limitations.

 
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

Featured Post

Free Tool: ZipGrep

ZipGrep is a utility that can list and search zip (.war, .ear, .jar, etc) archives for text patterns, without the need to extract the archive's contents.

One of a set of tools we're offering as a way to say thank you for being a part of the community.

  • 3
  • 3
Tackle projects and never again get stuck behind a technical roadblock.
Join Now