PDA

View Full Version : مشکل با ExecuteNonQuery در Datagridview Delete Button



eminem_13
دوشنبه 01 مهر 1387, 21:45 عصر
یک datagridview دارم که یک ستون delete button داره که اگه روی دکمه ی delete کلیک شود اطلاعات اون سطر باید پاک بشن. ولی روی دستور cmd.ExecuteNonQuery(); ارور میده. مشکلش چیه؟ باید چه کار کنم؟



private void Form1_Load(object sender, EventArgs e)
{
// TODO: This line of code loads data into the 'student2DataSet.table1' table. You can move, or remove it, as needed.
this.table1TableAdapter.Fill(this.student2DataSet. table1);
dataGridView1.AutoGenerateColumns = false;
dataGridView1.ReadOnly = true;
}

private void dataGridView1_CellClick(object sender, DataGridViewCellEventArgs e)
{
if (dataGridView1.CurrentCell.Value.ToString().Trim() == "delete")
{
dataGridView1.ReadOnly = false;
dataGridView1.AllowUserToDeleteRows = true;
SqlConnection con = new SqlConnection("Data Source=localhost;initial Catalog=Student2;integrated Security=True;");
con.Open();
string lname;
SqlCommand cmd = new SqlCommand();
lname = dataGridView1.CurrentRow.Cells[1].Value.ToString();
cmd.CommandText = "DELETE FROM table1 WHERE lastname=" + lname;
cmd.Connection = con;
cmd.ExecuteNonQuery();
this.student2DataSet.table1.Clear();
this.table1TableAdapter.Fill(this.student2DataSet. table1);
dataGridView1.Update();
con.Close();
dataGridView1.ReadOnly = true;
}
}

Sajjad.Aghapour
دوشنبه 01 مهر 1387, 22:11 عصر
دوست عزیز بهتره از SqlCommandBuilder استفاده کنی.به این صورت:


private void dataGridView1_CellContentClick(object sender, DataGridViewCellEventArgs e)
{
if (e.ColumnIndex == 2)
dataGridView1.Rows.RemoveAt(e.RowIndex);
SqlCommandBuilder builder = new SqlCommandBuilder(adapter);
adapter.Update(ds, "table1");
}

majid325
سه شنبه 02 مهر 1387, 01:16 صبح
چه خطايي ميگيره؟(متن خطا)
من فكر ميكنم فيلد lastname بايد string باشه يعني:

cmd.CommandText = "DELETE FROM table1 WHERE lastname='" + lname + "';";

به تك كوتيشن ها قبل و بعد lname دقت كن .