我在尝试删除行时遇到问题。
所有行都被选中并显示在ListBox
控件上。
然后,当调用btnObrisi_Click
事件(Obrisi = delete)时,从 中选择的项目ListBox
将被删除。
该项目实际上已从控件中删除,但该值并未从数据库中删除。
这是我正在使用的代码:
private string conString = @"Data Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|\Database1.mdf;Integrated Security=True;User Instance=True";
private SqlConnection con;
private SqlCommand com;
private DataTable dt;
private SqlDataAdapter da;
private DataTable SelectAll()
{
con = new SqlConnection(conString);
com = new SqlCommand();
dt = new DataTable();
da = new SqlDataAdapter();
com.Connection = con;
com.CommandType = CommandType.Text;
com.CommandText = "SELECT * FROM predmeti";
da.SelectCommand = com;
da.Fill(dt);
return dt;
}
private void Obrisi(int id)
{
con = new SqlConnection(conString);
com = new SqlCommand();
com.Connection = con;
com.CommandType = CommandType.Text;
com.CommandText = "DELETE FROM predmeti WHERE predmetID = @predmetID";
com.Parameters.AddWithValue("@predmetID", id);
try
{
con.Open();
com.ExecuteNonQuery();
MessageBox.Show("Obrisano");
}
catch(Exception ex)
{
MessageBox.Show(ex.Message);
}
finally
{
con.Close();
}
}
private void Citaj()
{
listBox1.ValueMember = "predmetID";
listBox1.DisplayMember = "ime_predmeta";
listBox1.DataSource = SelectAll();
}
private void btnOsvezi_Click(object sender, EventArgs e)
{
Citaj();
}
private void Form1_Load(object sender, EventArgs e)
{
Citaj();
}
private void btnObrisi_Click(object sender, EventArgs e)
{
int id = Convert.ToInt32(listBox1.SelectedValue);
Obrisi(id);
Citaj();
}