我解决了这个问题。在 gridview 我有模板列(我在 CommandArgument 中传递两个参数):
<asp:TemplateField>
<ItemTemplate>
<asp:ImageButton ToolTip="Delete" ID="button4" ButtonType="Image" ImageUrl="~/Projectimages/img_del.png" Text="" CommandName="Select" CommandArgument='<%#Eval("ID") + ";" +"Delete"%>' runat="server"/>
</ItemTemplate>
</asp:TemplateField>
在后面的代码中,我拆分 CommandArgument 并将值保存在变量中,然后在 SelectedIndexChanged 事件中使用它们:
string selectCommand = "";
int selectCommandID = -1;
protected void GridView_RowCommand(object sender, GridViewCommandEventArgs e)
{
if (e.CommandName == "Select")
{
if (!e.CommandArgument.ToString().Contains(";"))
selectCommand = "Select";
else
{
selectCommandID = Convert.ToInt32(e.CommandArgument.ToString().Split(';')[0]);
selectCommand = e.CommandArgument.ToString().Split(';')[1];
}
}
}
protected void GridView_SelectedIndexChanged(object sender, EventArgs e)
{
if (selectCommand == "Select")
{
//Select Code Here
}
else if (selectCommand == "Delete")
{
MyTestEntities context = new MyTestEntities();
Table1 selectedRow = context.Table1.Single(a => a.ID == selectCommandID);
context.Table1.DeleteObject(selectedRow);
context.SaveChanges();
EntityDataSource1.DataBind();
}
}
这行得通。您也可以使用它来更新 gridview 行。