I want to Delete Row from DataGridView in C# windows Form, my codes Works just for once then
if (dataGridView1.Columns[e.ColumnIndex].Name == "Delete")
{
try
{
using (con = new SqlConnection(C))
{
using (objCom = new SqlCommand("DELETE FROM Crud where Id = @Id;SELECT id as 'Customer Id' , Ch_Code as 'Customer Code' , Ch_Name as 'Customer Name',Ch_Type as 'Type' FROM Crud", con))
{
objCom.Parameters.AddWithValue("@id", dataGridView1.Rows[e.RowIndex].Cells[0].Value);
using ( objAdp = new SqlDataAdapter(objCom))
{
objAdp.Fill(DS,"xyz");
dataGridView1.DataSource = DS.Tables["xyz"].DefaultView;
}
}
}
}
catch (Exception EX)
{
MessageBox.Show(EX.Message);
}
}
it gives me exception
conversion failed when converting the nvarchar valur 'Delete' to data type int
The practice of using AddWithValue
is a good one for avoiding Sql Injections. but, when using the .Value
member, you need to make sure that your Value
won't contain a string while you need to pass integer for your dynamic transaction.
One thing to do is to convert your value to Int32, which will then be a valid int and perhaps won't return the error.
Your second option is to use SqlDbType.Int conversion. this way you will be sure to insert an integer acceptable by the database. like this:
(SqlDbType.Int)dataGridView1.Rows[e.RowIndex].Cells[0].Value;
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.