Deletion from a datagridview on the second attempt returns null exception if the column is hidden, but works fine if vissible.

George Panayiotou 20 Reputation points
2024-06-17T16:30:40.47+00:00

my program loads a table from sqlite3 and displays the content in a datagridview form with c#. I am sorting the table entries according to name and some values which gives out of order ID's to display in the datagridview. The program works fine if the ID column is visible. But when i use RangesDatagrid.Columns[0].Visible = false. This gives a null exception on the second time of deleting the first entry in the datagridview. When looking into the database, the entry is deleted dispite of the message. If i click on other entries in the gridview it works fine. Any ideas? This is the code for that part.

private void DeleteRangeBtn_Click(object sender, EventArgs e)

{

 if (!string.IsNullOrWhiteSpace(ComplexNameTxt.Text.Trim()) || !string.IsNullOrWhiteSpace(RangeNameTxt.Text.Trim()))

 {

     DialogResult result;

     if (RangesDatagrid.Rows.Count != 0)

     {

         string msg = "Do You Want To Permanently Delete The Selected Record?";

         string title = "Artemis: " + "Deletion Confirmation";

         result = MessageBox.Show(msg, title, MessageBoxButtons.YesNo, MessageBoxIcon.Question);

         if (result != DialogResult.Yes)

         {

             return;

         }

                 

         int rowValue = Convert.ToInt32(RangesDatagrid.Rows[RangesDatagrid.CurrentRow.Index].Cells[0].Value);

         try

         {

             bool isGood = GlobalConfig.Connection.DeleteRange(rowValue);

             if (!isGood)

             {

                 throw new ArgumentOutOfRangeException(nameof(sender), "Returned false by the DeleteRange method.");

             }

             else

             {

                 ClearFormData();

                 RefreshDataGridView();

                 DeleteCompleted();

             }

         }

         catch (Exception ex)

         {

             string msg2 = $"The Record Has NOT Been Deleted \nThe application has the following Error: {ex.Message}";

             string title2 = "Artemis: " + "Range Elevation";

             MessageBox.Show(msg2, title2, MessageBoxButtons.OK, MessageBoxIcon.Information);

         }

     }

 }

}

##############

public bool DeleteRange(int Id)

{

bool outcome;

//Connect to  database as per connection string in App.Config.

using (IDbConnection connection = new SqliteConnection(GlobalConfig.CnnString(db)))

{

    int affectedrows = connection.Execute("DELETE FROM RANGES WHERE RangeID = @RangeID", new { RangeID = Id });

    if (affectedrows > 0)

    {

        outcome = true;

    }

    else

    {

        outcome = false;

    }

}

return outcome;

}

#######################

private void RefreshDataGridView()

{

 if (AddNewRangeBtn.Text == "Cancel")

 {

     string msg = "Press the Cancel Button first before using Refresh!";

     string title = "Artemis: " + "Refresh";

     MessageBox.Show(msg, title, MessageBoxButtons.OK, MessageBoxIcon.Information);

     return;

 }

 List<RangeModel> rangeModels = GlobalConfig.Connection.GetRanges();

 availableRanges = rangeModels;

 RangesDatagrid.Columns.Clear();

 RangesDatagrid.AutoSize = true;

 RangesDatagrid.DataSource = availableRanges;

 DisplayDataGridRow(); //Pass the first row to the method and populate the textbox's.

 //Set the column headings.

 RangesDatagrid.Columns[0].HeaderText = "ID";

 RangesDatagrid.Columns[1].HeaderText = "Complex";

 RangesDatagrid.Columns[2].HeaderText = "Range Name";

 RangesDatagrid.Columns[3].HeaderText = "Distance";

 RangesDatagrid.Columns[4].HeaderText = "Elevation";

 RangesDatagrid.Columns[5].HeaderText = "Latitude";

 RangesDatagrid.Columns[6].HeaderText = "Direction";

 RangesDatagrid.Columns[7].HeaderText = "Notes";

 //RangesDatagrid.Columns[0].Visible = false; //################################

 RangesDatagrid.SelectionMode = DataGridViewSelectionMode.FullRowSelect;

}

hope this is sufficent!!!

Windows Forms
Windows Forms
A set of .NET Framework managed libraries for developing graphical user interfaces.
1,866 questions
C#
C#
An object-oriented and type-safe programming language that has its roots in the C family of languages and includes support for component-oriented programming.
10,534 questions
{count} votes

Accepted answer
  1. KOZ6.0 6,300 Reputation points
    2024-06-17T21:09:05.2466667+00:00

    The issue is with this line. When the second deletion occurs, RangesDatagrid.CurrentRow = null.

    int rowValue = Convert.ToInt32(RangesDatagrid.Rows[RangesDatagrid.CurrentRow.Index].Cells[0].Value);
    // delete process
    

    Modify it like this:

    if (RangesDatagrid.SelectedRows.Count > 0) {
        int rowIndex = RangesDatagrid.SelectedRows[0].Index;
        int rowValue = Convert.ToInt32(RangesDatagrid.Rows[rowIndex].Cells[0].Value);
        // delete process
    }
    

    or

    foreach (DataGridViewRow row in RangesDatagrid.SelectedRows) {
        int rowValue = Convert.ToInt32(RangesDatagrid.Rows[row.Index].Cells[0].Value);
        // delete process
    }
    

1 additional answer

Sort by: Most helpful
  1. George Panayiotou 20 Reputation points
    2024-06-18T16:16:52.3933333+00:00

    i tried the first way above but gave a null error as in the jpg.enc.first version..jpg

    The Third version seems to work. there is no need to add the check for row count as i am already checking prior to this. This is the working code. thanks for your help. int rowValue=0;

    foreach (DataGridViewRow row in RangesDatagrid.SelectedRows)

    {

    rowValue = Convert.ToInt32(RangesDatagrid.Rows[row.Index].Cells[0].Value);     
    

    }

    try

    {

     bool isGood = GlobalConfig.Connection.DeleteRange(rowValue);
    
     if (!isGood)
    
     {
    
         throw new ArgumentOutOfRangeException(nameof(sender), "Returned false by the DeleteRange method.");
    
     }
    
     else
    
     {
    
         ClearFormData();
    
         RefreshDataGridView();
    
         DeleteCompleted();
    
     }
    

    }

    0 comments No comments