0

I want to delete a record from a datagridview that's in one form by pressing a button in another form. But I am getting a nullreferenceexception was unhandled error. I am new to c# so if someone could write me the correct code I would really appreciate it.

Here's what I got so far.

private void button1_Click(object sender, EventArgs e)
{
    SqlConnection con = new SqlConnection(@" Data Source=HOME-D2CADC8D4F\SQL;Initial Catalog=motociclete;Integrated Security=True");

    SqlCommand cmd = new SqlCommand();
    for (int i = 0; i < dataGridView1.Rows.Count; i++)
    {
        DataGridViewRow dr = dataGridView1.Rows[i];
        if (dr.Selected == true)
        {
            dataGridView1.Rows.RemoveAt(i);
            try
            {
                con.Open();
                cmd.CommandText = "Delete from motociclete where codm=" + i + "";
                cmd.ExecuteNonQuery();
                con.Close();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.ToString());
            }
        }
    }
    this.Close();
}
3
  • Which line are you getting the exception at? I also noticed that you are referring to multiple forms here. A little more info on that front might help us. Commented May 18, 2013 at 20:09
  • I get the exception at this line: for (int i = 0; i < dataGridView1.Rows.Count; i++) Commented May 18, 2013 at 20:53
  • When you get an exception, you get a line number which tells you exactly where it happens. It's helpful if you set a breakpoint on that line and then run the code to find out what's happened to cause the exception. It's also extremely helpful if you identify that line for us in your question (not in the comments, but in the question itself) by commenting or otherwise marking that line so we don't have to guess. After all, you know exactly which line, because the exception gives you that information. Please share it with us. Commented May 19, 2013 at 3:28

5 Answers 5

1

Just invert the verse of the loop.

 for (int i = dataGridView1.Rows.Count - 1; i >= 0 ; i--)

In this way your loop is not affected by the changing number of rows

Also. This is the case where I would not open/close the connection at every command execution, and the command execution could be more performant if you use a parameter in this way

using(SqlConnection con = new SqlConnection(@" Data Source=HOME-D2CADC8D4F\SQL;Initial Catalog=motociclete;Integrated Security=True"))
using(SqlCommand cmd = new SqlCommand("Delete from motociclete where codm=@id", con))
{
    con.Open();
    cmd.Parameters.AddWithValue("@id", 0);
    for (int i = dataGridView1.Rows.Count-1; i >= 0; i++)
    {
        DataGridViewRow dr = dataGridView1.Rows[i];
        if (dr.Selected == true)
        {
            dataGridView1.Rows.RemoveAt(i);
            cmd.Parameters["@id"].Value = i;
            cmd.ExecuteNonQuery();
        }
    }
}
Sign up to request clarification or add additional context in comments.

3 Comments

The only possibility to get a NullReferenceException on the for(i = dateGridView1.Rows.Count-1 line is due to the Rows or the datagridview are null.
I have data in the sql table and it's shown in the datagridview , so i don't think that is the problem.
Then the only thing to help clear the problem is the debugger. Set a breakpoint on the offending line and check where is the null value
0

You are removing rows while iterating over them and that causes NullPointerException because when you remove row, count is changing but loop is still going for as long as initial count.

One way of doing it is creating temporary list of rows and delete them after:

List<DataGridViewRow> rowstodelete = new List<DataGridViewRow>();

for (int i = 0; i < dataGridView1.Rows.Count; i++)
{
    DataGridViewRow dr = dataGridView1.Rows[i];
    if (dr.Selected)
    {
        rowstodelete.Add(dr);
        try
        {
              con.Open();
              cmd.CommandText = "Delete from motociclete where codm=" + i + "";
              cmd.ExecuteNonQuery();
              con.Close();
         }
         catch (Exception ex)
         {
               MessageBox.Show(ex.ToString());
         }
    }
}

foreach (DataGridViewRow row in rowstodelete)
{
    dataGridView1.Rows.Remove(row);
}

2 Comments

I still get the same error at this line: for (int i = 0; i < dataGridView1.Rows.Count; i++) , after i < dataGridView1.Rows.Count
Is i coerced to a string automatically when you concatentate it to the delete statement?
0
private void button1_Click(object sender, EventArgs e)
{  int row =-1;   

      SqlConnection con = new SqlConnection(@" Data Source=HOME-D2CADC8D4F\SQL;Initial Catalog=motociclete;Integrated Security=True");

    SqlCommand cmd = new SqlCommand();
    row = new_tab_Object.CurrentCell.RowIndex;

            if (row!= (-1))
            {

                new_tab_Object.Rows.RemoveAt(row);                
                row = -1;
            try
            {
                con.Open();
                cmd.CommandText = "Delete from motociclete where codm=" + row + "";
                cmd.ExecuteNonQuery();
                con.Close();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.ToString());
            }
        }

    this.Close();
  }

thy this...

6 Comments

I get an error at row and new_tab_Object.CurrentCell.RowIndex
replace new_tab_Object with your gridview object dr for ex DataGridView dr = new DataGridView();
I still have the if(row) error. It says "cannot implicitly convert type 'int ' to 'bool'".Can you help me with that too?
It gives me a NullReferenceException at this line : row = new_tab_Object.CurrentCell.RowIndex;
for deleting the row you have to select one row or else it will throw an error..just select one row in your grid view and then press button it will work..
|
0

Why do you loop through all rows, use dataGridView1.SelectedRows:

for (int i = dataGridView1.SelectedRows.Count - 1; i >= 0; i--)
    dataGridView1.Rows.Remove(dataGridView1.SelectedRows[i]);

Also bind your data by using a DataTable and BindingSource.

Comments

0

I see that you are trying to access the grid of one form from another. Make sure that you get the reference of your form (the one with the grid) properly and refer the grid using that. to achieve that you may have to expose your grid object as public.

In your parent form expose a property for the grid

public GridView Grid
{
    return dataGridView1;
}

..and when you launch the new form (say ChildForm) do like this

Form child = new ChildForm(this);
child.Show();

Please make changes to your child form to use the constructor argument.

private Form m_ParentForm;
public ChildForm(Form child)
{
   m_ParentForm = child;
}

..and your loop would look like this

for (int i = 0; i < m_ParentForm.Grid.Rows.Count; i++)

Hope this helps.

1 Comment

I thing it might be the connection from one form to another. Do i have to write Form parentForm = refObject; in the 1st form? And what is refObject?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.