When selecting a line for deletion, these errors appear, what is the problem?
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();
}
CodePudding user response:
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.