如何从数据视图中删除行(不使用DataView.Delete)?

3

如何从DataView中删除行

目前我正在使用以下代码:

DataView DV = new DataView();

//填充数据

DV.Delete(5);

但是对于动态行,我们不知道任何特定值的行索引。

例如,我有100条记录(行)在DataView中, 我希望保留除某个值X之外的所有记录。 如何从DataView中删除特定的值X呢?

请提供建议。

5个回答

3
如果您想要隐藏行,使用RowFilter就可以了解决问题。 编辑: 如果您想从DataTable中将它们移除,请使用DataTable的Select方法,并删除找到的DataRows。

Erno,谢谢你,但我不想隐藏,我只想删除这一行,这可能吗? - ertjain
@ertjain,所以你想从DataSet中删除它们?DataView只是一个“视图”? - Emond
Erno,谢谢你。我尝试了你的建议,猜猜它奏效了! - ertjain

0

尝试访问DataRow,然后执行删除操作。

DV.Row.Delete()

0
你可以创建一个已排序的 DataViewvar dv = new DataView(dataTable, "id", null, DataViewRowState.CurrentRows); 然后找到行索引: var index = dv.Find(id); if (index > -1) dv.Delete(index);

0
假设myRow是类型为System.Data.DataRow,您可以这样做:

int index = DV.Table.Rows.IndexOf(myRow);
DV.Delete(index);

-2

试试这个:

protected void gridview1_RowDeleting(object sender, GridViewDeleteEventArgs e)
{
    using (SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["myConnectionString"].ToString()))
    {
        // Create a command object. 
        SqlCommand cmd = new SqlCommand();

        // Assign the connection to the command. 
        cmd.Connection = conn;

        // Set the command text 
        // SQL statement or the name of the stored procedure  
        cmd.CommandText = "DELETE FROM Products WHERE ProductID = @ProductID";

        // Set the command type 
        // CommandType.Text for ordinary SQL statements;  
        // CommandType.StoredProcedure for stored procedures. 
        cmd.CommandType = CommandType.Text;

        // Get the PersonID of the selected row. 
        string strProductID = gridview1.Rows[e.RowIndex].Cells[0].Text;

        // Append the parameter. 
        cmd.Parameters.Add("@ProductID", SqlDbType.BigInt).Value = strProductID;

        // Open the connection and execute the command. 
        conn.Open();
        cmd.ExecuteNonQuery();
    }

    // Rebind the GridView control to show data after deleting. 
    BindGridView();
}

欢迎来到[so]。最好的做法是在段落中提供代码的简短解释,除了代码中的注释。更好的答案会增加你的声望,从而获得更多的赞。请参见[answer]获取更多信息。 - Qantas 94 Heavy

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接