2014-03-31 66 views
0

我試圖做的是把一組記錄從數據庫到一個列表框,從列表框中選擇行會顯示在列表框中的另一個其子記錄和刪除選定的子記錄時,按鈕被按下。第一部分工作正常,我在刪除時遇到問題,它不會發生。爲什麼?數據集將不會刪除

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

請確保您有DataSet下的Update和Delete命令。還要檢查數據庫中的表中是否有主鍵。

+0

Checked.Added 'daf.DeleteCommand =新的SqlCommand( 「從膜刪除其中Id = @fid」); daf.DeleteCommand.Parameters.Add( 「@ FID」,SqlDbType.Int); daf.DeleteCommand.Parameters.AddWithValue( 「@ FID」,IDD);' – Matt

+0

你在哪裏仍然看到列,DS/listBoxchildren,兩者兼而有之? –

+0

是,代碼主要是發現問題同樣 – Matt