0

When selecting a line for deletion, these errors appear, what is the problem?

enter image description here

private void button3_Click(object sender, EventArgs e)
{
    con = new SqlConnection(@"Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=E:\desk\new\abusalem\abusalem\Database1.mdf;Integrated Security=True");
    cmd.Connection = con;
    cmd.CommandType = CommandType.Text;
    cmd.CommandText = "delete from datauser where id= "+dataGridView1.CurrentRow.Cells[0].Value;
    con.Open();
    cmd.ExecuteNonQuery();
    con.Close();
    filltable();
}
2
  • 1
    welcome to stackoverflow ibrahim. where is this cmd being created/initialized? is it a property of Page? Commented Jun 24, 2022 at 6:33
  • Does this answer your question? What is a NullReferenceException, and how do I fix it? Commented Jun 24, 2022 at 9:24

1 Answer 1

2

Here is a conceptual path to follow. The example is setup for a DataTable, if not using a DataTable but not setting the DataGridView.DataSource consider what is shown below. There is no need to reload the DataGridView once a row has been removed.

Setup a BindingSource scoped form level, set the DataSource to what you are using to populate the DataGridView currently e.g. a Datatable then dataGridView1.DataSource = someBindingSource. Set the primary key column to hidden so it is not seen.

If no primary key than adjust dataGridView1.CurrentRow.Cells[0].Value the code below to accept that value.

To remove a row, in the button click event. Here I have Id as the key.

public class Operations
{
    private static string _connectionString =
        @"Data Source=(LocalDB)\MSSQLLocalDB;" + 
        @"AttachDbFilename=E:\desk\new\abusalem\abusalem\Database1.mdf;" + 
        "Integrated Security=True";

    public static bool Remove(int id)
    {
        using (var cn = new SqlConnection(_connectionString))
        {
            using (var cmd = new SqlCommand() {Connection = cn})
            {
                cmd.CommandText = "delete from datauser where id=@Id";
                cmd.Parameters.Add("@Id", SqlDbType.Int).Value = id;
                return cmd.ExecuteNonQuery() == 1;
            }
        }
    }
}

Form code

private BindingSource someBindingSource = new BindingSource();
private void RemoveButton_Click(object sender, EventArgs e)
{
    DataRow row = ((DataRowView)someBindingSource.Current).Row;
    if (Operations.Remove(row.Field<int>("id")))
    {
        someBindingSource.RemoveCurrent();
    }
}

In the future provide enough code so we have a idea what exactly is being done in regards to how the DataGridView gets loaded.

Sign up to request clarification or add additional context in comments.

Comments

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.