DataSet不会删除

时间:2014-03-31 12:45:31

标签: c# database listbox

我尝试做的是将数据库中的一组记录放入列表框,从该列表框中选择一行将在另一个列表框中显示其子记录,并在按钮为时删除所选的子记录第一部分工作正常,我在删除时遇到了麻烦,但事情并没有发生。为什么会这样?

    public Form1()
    {
      InitializeComponent();
      SqlCommand comm = new SqlCommand();
      comm.CommandText = "Select * From Director;";
      comm.Connection = conn;
      da.SelectCommand = comm;
      da.Fill(ds, "Director");
      comm.ExecuteNonQuery();

      SqlCommand commf = new SqlCommand();
      commf.CommandText = "Select * From Film;";
      commf.Connection = conn;
      daf.SelectCommand = commf;
      daf.Fill(ds, "Film");
      commf.ExecuteNonQuery();
      ds.Tables["Director"].Constraints.Add("PK_Director", ds.Tables["Director"].Columns["id"], true);
      ds.Tables["Film"].Constraints.Add("PK_Film", ds.Tables["Film"].Columns["id"], true);
      ds.Relations.Add("fk_FilmDir", ds.Tables["Director"].Columns["ID"], ds.Tables["Film"].Columns["Id_director"]);

      SqlCommandBuilder builder = new SqlCommandBuilder(daf);
      daf.DeleteCommand = builder.GetDeleteCommand();
      listBoxparent.DataSource = d
      listBoxparent.DisplayMember = "Director.FirstName";            
      listBoxparent.ValueMember = "Director.FirstName";
      listBoxchildren.DataSource = ds;   
      listBoxchildren.DisplayMember = "Director.fk_FilmDir.title";

      conn.Close();
      }
private void button1_Click(object sender, EventArgs e)
       {
         int ind = listBoxchildren.SelectedIndex;
         listBoxchildren.DataSource = null;

         int idd= ds.Tables["Film"].Rows[ind].Field<int>("ID");
         ds.Tables["Film"].Rows.Remove(ds.Tables["Film"].Rows.Find(idd));    
         daf.Update(ds, "Film");

         listBoxchildren.DataSource = ds;
         listBoxchildren.DisplayMember = "Director.fk_FilmDir.title";
        }

1 个答案:

答案 0 :(得分:1)

确保DataSet下有更新和删除命令。还要检查数据库中的表中是否有主键。