【问题标题】:I can't delete the selected row in a gridView from DataSet我无法从 DataSet 中删除 gridView 中的选定行
【发布时间】:2012-09-15 07:04:54
【问题描述】:

我的表单中有一个 gridView 和一个按钮,用于删除此 gridView 以及 DataSet 中的选定行。

这是我试过的代码:

DataRow row = gridView1.GetDataRow(gridView1.GetSelectedRows()[0]);

for (int i = 0; i < connexion.ds.Tables["Auteur"].Rows.Count; i++)
    if (row[0].ToString() == connexion.ds.Tables["Auteur"].Rows[i][0].ToString())
        connexion.ds.Tables["Auteur"].Rows[i].Delete();

for (int i = 0; i < connexion.ds.Tables["AuteurGV"].Rows.Count; i++)
    if (row[0].ToString() == connexion.ds.Tables["AuteurGV"].Rows[i][0].ToString())
        connexion.ds.Tables["AuteurGV"].Rows[i].Delete();

SqlCommandBuilder cmb = new SqlCommandBuilder(da);
da.Update(connexion.ds, "Auteur");

gridControl1.DataSource = connexion.ds.Tables["AuteurGV"];

但它在第 6 行给了我一个错误:

已删除的行信息无法通过行访问。

【问题讨论】:

    标签: c# winforms gridview dataset


    【解决方案1】:

    改成

    DataRow row = gridView1.GetDataRow(gridView1.GetSelectedRows()[0]); 
    
    string valToDelete = row[0].ToString();
    
    for (int i = 0; i < connexion.ds.Tables["Auteur"].Rows.Count; i++) 
        if (valToDelete == connexion.ds.Tables["Auteur"].Rows[i][0].ToString()) 
             connexion.ds.Tables["Auteur"].Rows[i].Delete(); 
    
    for (int i = 0; i < connexion.ds.Tables["AuteurGV"].Rows.Count; i++) 
        if (valToDelete == connexion.ds.Tables["AuteurGV"].Rows[i][0].ToString()) 
             connexion.ds.Tables["AuteurGV"].Rows[i].Delete(); 
    
    SqlCommandBuilder cmb = new SqlCommandBuilder(da); 
    da.Update(connexion.ds); 
    gridControl1.DataSource = connexion.ds.Tables["AuteurGV"]; 
    

    问题出在第二个 for 循环中,您已经删除了从中提取键值以用于比较的行。这是不可能的,因为当 RowState 属性更改为 Delete 时,您无法使用该行中的任何值。
    我还更改了 da.Update 调用以更新所有数据集,而不仅仅是 Auteur 表。

    【讨论】:

    • 我在删除按钮中解决了这个问题,但是当我单击 gridView 中的某行以从数据集中提取信息时遇到了同样的问题,这是我使用的代码:DataRow row = gridView1.GetDataRow(gridView1.GetSelectedRows()[0]); for(int i=0; i&lt;connexion.ds.Tables["Auteur"].Rows.Count; i++) if (row[0].ToString() == connexion.ds.Tables["Auteur"].Rows[i][0].ToString()) { nomAuteurBox.Text = connexion.ds.Tables["Auteur"].Rows[i][1].ToString(); //......}
    • gridControl 和 gridView 是不同的控件吗?似乎您使用 gridView 删除了一行并重新绑定了 gridControl。
    • 您也从 Auteur 和 AuteurGV 表中删除,但只更新 Auteur 表
    猜你喜欢
    • 2014-02-12
    • 1970-01-01
    • 1970-01-01
    • 2013-03-27
    • 1970-01-01
    • 1970-01-01
    • 2021-05-15
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多