如何在不使用SqlDataSource,ObjectDataSource等的情况下删除gridview和底层数据源中的行
题
我有一个GridView,我通过调用一个方法返回一个包含两列的数据表来填充它。在我返回数据表之后,我将它绑定到gridview并显示它。
我没有使用SqlDataSource或ObjectDataSource,因此从gridview中删除行以及数据库中的基础数据的正确方法是什么。我只需要从一个名为portfolio的表中删除。它有3列ID,它是唯一键,PortfolioID和PortfolioName。数据表返回PortfolioName和项目组合中的项目数。我想我可以在Row_Deleting事件中执行此操作,我会执行以下操作:
DELETE * FROM Portfolio WHERE PortfolioID = @PortfolioID
我是否在正确的轨道上,我将如何做到这一点?我可以将PortfolioID绑定到GridView DataKey属性(执行此操作的正确语法是什么?)
解决方案
我假设您在按下按钮时删除了一行。如果是这样,我通常会这样做:
<asp:GridView ID="myGrid" runat="server" DataKeyNames='PortfolioID' OnRowCommand="dgStudent_RowCommand">
<Columns>
<asp:ButtonField ButtonType="Button" CommandName="Delete" Text="Delete"></asp:ButtonField>
</Columns>
</asp:GridView>
然后在您的代码隐藏中:
protected void myGrid_RowCommand(object sender, GridViewCommandEventArgs e)
{
// create and open DB connection
int PortfolioID = (int)myGrid.DataKeys[Convert.ToInt32(e.CommandArgument)].Value;
DeleteRow(PortfolioID); // your implementation
myGrid.DataBind();
}
DeleteRow
是你行删除的实现(可能是你上面的SQL)。 myGrid是你的网格。 PortfolioID
是主键。这也假设网格中的唯一按钮是删除按钮。如果您有多个按钮,则需要检查 e.CommandName ==&quot; Delete&quot;
以确保获得删除按钮。
其他提示
我可能会进一步抽象出DB调用。我可能会在行更改完成后处理行。对于后处理,您可以检查rowstate以确定如何处理行中的数据。
据我了解,您要从数据库表中删除数据网格视图中的行。这意味着您要从某个数据库中删除和表记录。 执行此操作的最佳方法是将文本框放在某处并为您的datagridview创建事件(在行选择事件上)。这样,当您选择要删除的行时,该行的ID将被发送到文本框(这将被编码)。获得要删除的行的id后,只需添加一个按钮即可删除数据库中的记录并再次绑定datagridview。
private void dataGridView1_CellContentClick(object sender, DataGridViewCellEventArgs e)
{
this.txt_portfolioId.Text=dataGridView1.CurrentRow.Cells["portfolioID"].Value.ToString();
}
private void btn_Delete(object sender, EventArgs e)
{
//You need to connect to database(regular database connection this connection string and sqlcommand and add this sqlquerry:
从yourtable删除* portfolioid ='&quot; + Convert.ToInt32(this.portfolioId.Text)+&quot;';
}