I have this form that takes these information from user @ID, @From, @To, @Title, @Message
. Then it insert them into a database table.
How can I delete a certain data using the @ID
? User will have a dataGridView1
with all the datatable
, then by getting the CurrentCell
it will delete this certain data.
private void delet_button_Click(object sender, EventArgs e)
{
int i = dataGridView1.CurrentCell.RowIndex;
string strid = dataGridView1[0, i].Value.ToString();
//MessageBox.Show(strid);
int id = Convert.ToInt32(strid);
SqlCommand cmd = new SqlCommand();
cmd.Connection = con;
cmd.CommandType = CommandType.Text;
cmd.CommandText = "Delete * from MessagesTable where [ID]=@ID ";
cmd.Parameters.AddWithValue("@ID", id);
MessageBox.Show("Message was deleted");
BindGrid();
}
CodePudding user response:
You are almost certainly going about this all wrong. You should start with a DataTable
. If appropriate, you can query the database to populate it by calling Fill
on a data adapter. You can then bind the table to your DataGridView
via a BindingSource
, which you would add in the designer, e.g.
var table = new DataTable();
using (var adapter = new SqlDataAdapter("SQL query here", "connection string here"))
{
adapter.Fill(table);
}
BindingSource1.DataSource = table;
DataGridView1.DataSource = BindingSource1;
You then mark the current row as deleted by calling RemoveCurrent
on the BindingSource
. That will hide the row in the grid but it won't affect the database at that stage. To save the changes to the database, you call Update
on an appropriately configured data adapter, which may be the same one you called Fill
on in the first place. You could call Update
to save the change as soon as the user deletes the row or you could just cache all changes locally - inserts, updates and deletes - and then call Update
once at the end to save all the changes together.
CodePudding user response:
Add cmd.ExecuteNonQuery();
private void delet_button_Click(object sender, EventArgs e)
{
int i = dataGridView1.CurrentCell.RowIndex;
string strid = dataGridView1[0, i].Value.ToString();
//MessageBox.Show(strid);
int id = Convert.ToInt32(strid);
SqlCommand cmd = new SqlCommand();
cmd.Connection = con;
cmd.CommandType = CommandType.Text;
cmd.CommandText = "Delete from MessagesTable where [ID]=@ID ";
cmd.Parameters.AddWithValue("@ID", id);
cmd.ExecuteNonQuery();
MessageBox.Show("Message was deleted");
BindGrid();
}