在GridView的刪除按鈕,這是我的代碼:問題在Visual Studio
private void Bind()
{
SqlConnection con = new SqlConnection(@"Data Source=(LocalDB)\v11.0;AttachDbFilename=C:\Users\Dido\documents\visual studio 2012\Projects\CourseProjectCars\CourseProjectCars\DataCars.mdf;Integrated Security=True;Connect Timeout=30");
con.Open();
SqlDataAdapter da = new SqlDataAdapter("select * from SuperCars", con);
DataTable dt = new DataTable();
da.Fill(dt);
dataGridView1.DataSource = dt;
con.Close();
}
private void button4_Click(object sender, EventArgs e)
{
SqlConnection con = new SqlConnection(@"Data Source=(LocalDB)\v11.0;AttachDbFilename=C:\Users\Dido\documents\visual studio 2012\Projects\CourseProjectCars\CourseProjectCars\DataCars.mdf;Integrated Security=True;Connect Timeout=30");
SqlCommand delcmd = new SqlCommand();
if (dataGridView1.Rows.Count > 1 && dataGridView1.SelectedRows[0].Index != dataGridView1.Rows.Count - 1)
{
delcmd.CommandText = "DELETE FROM SuperCars WHERE Car='%" + dataGridView1.SelectedRows[0].Cells[0].Value.ToString() + "%'";
con.Open();
delcmd.Connection = con;
delcmd.ExecuteNonQuery();
con.Close();
dataGridView1.Rows.RemoveAt(dataGridView1.SelectedRows[0].Index);
MessageBox.Show("Row Deleted");
}
Bind();
}
我想提出一個刪除按鈕在我的應用程序。當我選擇一行並單擊刪除按鈕時,它會拋出以下異常:
索引超出範圍。必須是非負數且小於集合的大小。
我粘貼在上面。請看一下。 – Cathy
是的,我覺得當你點擊刪除的時候GridView行沒有被選中,那是有機會得到錯誤的。 –
謝謝,這有助於更多! – Cathy