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
Solved

Datagridview delete button click event

Posted on 2010-11-26
5
1,807 Views
Last Modified: 2012-05-10
I have a datagridview on my form populated from a dataset which is pulled from an sql database. Each row in the datagridview has a delete button. I need to capture the button click event and which row in the datagridview it was clicked so it can be deleted from the database.
//View all movies in the database
        private void btnViewAllMovies_Click(object sender, EventArgs e)
        {
            DAL data = new DAL();
            DataSet ds = data.getAllData("select * from tblMovies");
            dgvAllMovies.DataSource = ds.Tables[0];
            CreateDelete();

          public void CreateDelete()
        {
            //Creates the delete column and adds the delete buttons for each row
            var buttonCol = new DataGridViewButtonColumn();
            buttonCol.Name = "Delete";
            buttonCol.HeaderText = "Delete";
            buttonCol.Text = "Delete";
            buttonCol.UseColumnTextForButtonValue = true;
            buttonCol.DisplayIndex = 0;

       //Button click event test - Not working
        private void dgvAllMovies_CellClick(object sender, DataGridViewCellEventArgs e)
        {
            MessageBox.Show("Click");

        }

Open in new window

0
Comment
Question by:98fatboyrider
  • 3
5 Comments
 
LVL 16

Accepted Solution

by:
kris_per earned 250 total points
ID: 34218427

Sample code below:
private void btnViewAllMovies_Click(object sender, EventArgs e)
        {
            DAL data = new DAL();
            DataSet ds = data.getAllData("select * from tblMovies");
            dgvAllMovies.DataSource = ds.Tables[0];

            // Add Button Column
            DataGridViewButtonColumn buttonCol = new DataGridViewButtonColumn();
            buttonCol.Name = "Delete";
            buttonCol.HeaderText = "Delete";
            buttonCol.Text = "Delete";
            buttonCol.UseColumnTextForButtonValue = true;
            buttonCol.DisplayIndex = 0;
            dgvAllMovies.Columns.Add(buttonCol);

            // add event handler for cell content click
            dgvAllMovies.CellContentClick += new DataGridViewCellEventHandler(dgvAllMovies_CellContentClick);            
        }

        void dgvAllMovies_CellContentClick(object sender, DataGridViewCellEventArgs e)
        {
            if (e.ColumnIndex == 0) // only if Delete button column/here it is first column
            {
                // remove the row in the datasource which 
                // will automatically remove row from the grid                

                DataGridViewRow grigRow = dgvAllMovies.Rows[e.RowIndex];
                DataRowView drv = grigRow.DataBoundItem as DataRowView;
                DataTable dt = (DataTable)dgvAllMovies.DataSource;
                dt.Rows.Remove(drv);
            }
        }

Open in new window

0
 
LVL 16

Expert Comment

by:kris_per
ID: 34218509

In addtion to the above code which will remove the row from Grid and datasource, you need to add code to actually save the changes to database.
Have a Save button and on clicking that button have the below code:
private void buttonSave_Click(object sender, EventArgs e)
        {
            DataTable dt = (DataTable)dgvAllMovies.DataSource;

            DAL data = new DAL();
            data.SaveData(dt, "select * from tblMovies");
        }

// ADD NEW SaveData METHOD to DAL class
public class DAL
        {
            // your DAL class might have other code here...

            // new method
            public void SaveData(DataTable dataTable, string sourceQuery)
            {
                using (SqlConnection conn = new SqlConnection(connectionString))
                {
                    conn.Open();

                    SqlDataAdapter adapter = new SqlDataAdapter();

                    adapter.SelectCommand = new SqlCommand(sourceQuery, conn);

                    SqlCommandBuilder commandBuilder = new SqlCommandBuilder(adapter);

                    adapter.Update(dataTable);
                }
            }
        }

Open in new window

0
 

Author Comment

by:98fatboyrider
ID: 34218611
This is close, but the line below is giving a couple of errors. Suggestions?
dt.Rows.Remove(drv);
//The best overloaded method match for 'System.Data.DataRowCollection.Remove(System.Data.DataRow)' has some invalid arguments
//Argument '1': cannot convert from 'System.Data.DataRowView' to 'System.Data.DataRow'

Open in new window

0
 
LVL 12

Expert Comment

by:jagssidurala
ID: 34218783
0
 
LVL 16

Assisted Solution

by:kris_per
kris_per earned 250 total points
ID: 34218903
Sorry, correct the line to:

dt.Rows.Remove(drv.Row);
0

Featured Post

Free Tool: IP Lookup

Get more info about an IP address or domain name, such as organization, abuse contacts and geolocation.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

Question has a verified solution.

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

Suggested Solutions

Title # Comments Views Activity
Video Player 12 27
C# winforms programmitically move panels 6 43
IEnumerable<T> to a List<T> 8 37
How can I do Unit Testing with Session ? 1 9
Article by: Najam
Having new technologies does not mean they will completely replace old components.  Recently I had to create WCF that will be called by VB6 component.  Here I will describe what steps one should follow while doing so, please feel free to post any qu…
Exception Handling is in the core of any application that is able to dignify its name. In this article, I'll guide you through the process of writing a DRY (Don't Repeat Yourself) Exception Handling mechanism, using Aspect Oriented Programming.
With Secure Portal Encryption, the recipient is sent a link to their email address directing them to the email laundry delivery page. From there, the recipient will be required to enter a user name and password to enter the page. Once the recipient …

840 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