0

I haven't done too much with DataGridViews in C# form applications so my approach is a rookie one I'm sure. Any help would be awesome!

My form is displaying the DataGridView for my database, and I want to give the user the option of deleting a particular row that is selected and then saving the changes.

Here is my code:

    private void btnDeleteCustomer_Click(object sender, EventArgs e)
    {
        foreach (DataGridViewRow item in this.dataGridView1.SelectedRows)
        {
            dataGridView1.Rows.RemoveAt(item.Index);
            dataGridView1.SelectAll();

        }
    }

    private void btnSelectAll_Click(object sender, EventArgs e)
    {
        dataGridView1.SelectAll();
    }

I am attempting to delete the selected row, then select all of the remaining rows, and then save the selected remaining rows with the click of one button. I'm sure there is a better way of doing so but I can't find a solution that works. Thanks!

abatishchev
  • 98,240
  • 88
  • 296
  • 433
Cory Hull
  • 31
  • 5
  • why would you need to select all after deleting one row. Also, what do you mean by saving the remaining rows, are you saving it into a database, or a file, or you just trying to refresh the gridview. – faljbour Mar 05 '15 at 00:03
  • I am selecting all after deleting because I plan to save the selected rows back to the database but I am unsure of how to do this. – Cory Hull Mar 05 '15 at 00:11
  • but you do not need to select all, all you need is to loop over all of the remaining rows and save to the database, – faljbour Mar 05 '15 at 00:12
  • How would I then save the remaining to the database? – Cory Hull Mar 05 '15 at 00:15
  • Why would he loop over and save items while deleting a row? – Abdul Saleem Mar 05 '15 at 07:55
  • @Sayka I am more looking to save all of the rows to the database after a deletion. I haven't done this before so I was thinking to save a selected row. Do you know how to save a selected row from gridview to database? – Cory Hull Mar 06 '15 at 00:09

2 Answers2

0

I don't see that there's a big difference, But you could delete rows in different ways, You might want to consider using extension methods to extend the datagridview functionality with ease, For example:

public static class DataGridViewExtensions
    {
        public static void DeleteSelectedRows(this DataGridView dgv)
        {
            foreach (DataGridViewRow row in dgv.SelectedRows)
                dgv.Rows.Remove(row);
        }
    }

And you could simply call this function like this

dataGridView1.DeleteSelectedRows();
Khaled El Kholy
  • 136
  • 1
  • 4
  • Thanks Khaled! I am getting this error after using the dataGridView1.DeleteSelectedRows(); Error 1 'System.Windows.Forms.DataGridView' does not contain a definition for 'DeleteSelectedRows' and no extension method 'DeleteSelectedRows' accepting a first argument of type 'System.Windows.Forms.DataGridView' could be found (are you missing a using directive or an assembly reference?) – Cory Hull Mar 05 '15 at 00:14
  • Please make sure that they are both (the method definition / caller) under the same namespace, If not consider using the namespace you have defined – Khaled El Kholy Mar 05 '15 at 00:28
  • Your form cannot find the extension method you have, because it's under different namespace, You may be missing a "using directive" – Khaled El Kholy Mar 05 '15 at 00:38
0
        Int32 rowToDelete = dataGridView1.Rows.GetFirstRow(DataGridViewElementStates.Selected);
        if (rowToDelete > -1)
        {
          dataGridView1.Rows.RemoveAt(rowToDelete);

          dataGridView1.Invalidate();
          string lastName = (string)dataGridView1.Rows[rowToDelete].Cells[0].Value;
          string firstName = (string)dataGridView1.Rows[rowToDelete].Cells[1].Value;
          string email = (string)dataGridView1.Rows[rowToDelete].Cells[2].Value;
          string phoneNumber = (string)dataGridView1.Rows[rowToDelete].Cells[3].Value;
          string address = (string)dataGridView1.Rows[rowToDelete].Cells[4].Value;
          string instagram = (string)dataGridView1.Rows[rowToDelete].Cells[5].Value;
          string carMake = (string)dataGridView1.Rows[rowToDelete].Cells[6].Value;
          string carModel = (string)dataGridView1.Rows[rowToDelete].Cells[7].Value;
          string additionalNotes = (string)dataGridView1.Rows[rowToDelete].Cells[8].Value;
          SqlConnection CustomerInfo = new SqlConnection("Data Source=.\\SQLEXPRESS;AttachDbFilename=C:\\Users\\Cory\\Desktop\\DeluxWrapsWindows\\DeluxWrapsWindows\\DeluxWraps.mdf;Integrated Security=True;User Instance=True");
          {
             SqlCommand xp = new SqlCommand("DELETE FROM CustomerInfo WHERE LastName='" + lastName + "' AND FirstName='" + firstName + "'");

             CustomerInfo.Open();
             xp.ExecuteNonQuery();
             CustomerInfo.Close();
          }
        }
faljbour
  • 1,367
  • 2
  • 8
  • 15
  • When I add the code I have a squiggly line under "Cell". I'm not sure why this is. Also, is the third piece of code for the saving portion? I really appreciate your help! – Cory Hull Mar 05 '15 at 00:30
  • how do you populate the dataGridView, post the code for that, I can modify the answer based on the number of columns the dataGrid have. each cell belongs to a column in the dataGridView. – faljbour Mar 05 '15 at 00:35
  • I added the code that I have below the code that you posted. I'm assuming that you are looking for this. I user a dataGridView to post the data directly from the database from Visual Studios so I didn't write any of that code myself. – Cory Hull Mar 05 '15 at 00:45
  • you would need to find how you would save this code into the database, the code you posted only the designer code generated by Visual Studio, I only kept the dataGridView section and modified the answer based on the the number of columns the designer is indicating – faljbour Mar 05 '15 at 01:11
  • Thanks once again Faljbour! I am still trying to get rid of the error with the word "Cel'" in the code. any clue to what is causing this? – Cory Hull Mar 05 '15 at 01:19
  • Error 1 'System.Windows.Forms.DataGridViewRow' does not contain a definition for 'Cell' and no extension method 'Cell' accepting a first argument of type 'System.Windows.Forms.DataGridViewRow' could be found (are you missing a using directive or an assembly reference?) – Cory Hull Mar 05 '15 at 01:28
  • Cory, there is nothing in the code that I posted that has DataGridViewRow, it is dataGridView1.Rows where in the code there is such an object. – faljbour Mar 05 '15 at 01:32
  • It's weird that it says that because I copied the code that you gave me exactly. Copied and pasted. So my code is identical to yours but throws that error where it only specified the "DataGridView" and not the additional 1 – Cory Hull Mar 05 '15 at 01:39
  • if you click on the error, it should take you to the exact line where the error is occurs, it should list the line number too. – faljbour Mar 05 '15 at 01:41
  • The error occurs every time that the word "Cells" is used in the code that I used. – Cory Hull Mar 05 '15 at 03:57
  • Ok, after looking around, it seems the Cells is not supported for any .NET Framework version of less than 4.0, so you must be using .NET 3.5 or 3.0. I would recommend updating you project reference .NET 4.0 or 4.5. – faljbour Mar 05 '15 at 04:22
  • I will try that out. I am assuming that I can do this through Visual Studios. I really appreciate your help and I have learned a lot! I can't thank you enough for your time and patience. – Cory Hull Mar 05 '15 at 04:29
  • Yes, through your project References, right click on it then select Add Reference -> Assemblies -> Framework -> System make sure it is revision 4.0 or higher. Glad to help – faljbour Mar 05 '15 at 04:35
  • I checked under the project reference and I am actually using the .Net Framework 4.0 – Cory Hull Mar 06 '15 at 00:13
  • It must be pointing to the incorrect .NET version, I am using the exact code in multiple projects and it I do not have that issue, if you solve the .NET issue, you should be able to compile the oce – faljbour Mar 06 '15 at 00:24
  • Cory, you are welcome to zip up the project and email it to me to solve the issue, omit the bin and the object directories. email it same user name @yahoo.com. I think we posted too many comments, let's take this offline – faljbour Mar 06 '15 at 02:52