如何从DataView中删除行
目前我正在使用以下代码:
DataView DV = new DataView();
//填充数据
DV.Delete(5);
但是对于动态行,我们不知道任何特定值的行索引。
例如,我有100条记录(行)在DataView中, 我希望保留除某个值X之外的所有记录。 如何从DataView中删除特定的值X呢?
请提供建议。
如何从DataView中删除行
目前我正在使用以下代码:
DataView DV = new DataView();
//填充数据
DV.Delete(5);
但是对于动态行,我们不知道任何特定值的行索引。
例如,我有100条记录(行)在DataView中, 我希望保留除某个值X之外的所有记录。 如何从DataView中删除特定的值X呢?
请提供建议。
尝试访问DataRow,然后执行删除操作。
DV.Row.Delete()
DataView
:
var dv = new DataView(dataTable, "id", null, DataViewRowState.CurrentRows);
然后找到行索引:
var index = dv.Find(id);
if (index > -1)
dv.Delete(index);
myRow
是类型为System.Data.DataRow
,您可以这样做:
int index = DV.Table.Rows.IndexOf(myRow);
DV.Delete(index);
试试这个:
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();
}