我有一个GridView,它显示数据库中的项目。当我单击“删除”链接按钮时,我想从数据库中删除项目:
<asp:GridView ID="gvCategories" AutoGenerateColumns="False" runat="server" ItemType="webLicenta.Category"
SelectMethod="GetCategories" AppendDataBoundItems="true" CssClass="table table-striped table-bordered table-hover">
<Columns>
<asp:BoundField DataField="CategoryID" HeaderText="Nr. Categorie" SortExpression="CategoryID" />
<asp:BoundField DataField="CategoryName" HeaderText="Denumire categorie" SortExpression="CategoryName" />
<asp:TemplateField HeaderText="Opțiuni">
<ItemTemplate>
<asp:LinkButton ID="lnkDeleteCategory" runat="server">Delete</asp:LinkButton>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
我尝试了这个,但没有结果:
protected void gvCategories_SelectedIndexChanged(object sender, EventArgs e)
{
using (var _db = new webLicenta.MagazinDBEntities())
{
int categoryId = Convert.ToInt16(gvCategories.SelectedValue);
var myItem = (from c in _db.Categories where c.CategoryID == categoryId select c).FirstOrDefault();
if (myItem != null)
{
_db.Categories.Remove(myItem);
_db.SaveChanges();
string pageUrl = Request.Url.AbsoluteUri.Substring(0, Request.Url.AbsoluteUri.Count() - Request.Url.Query.Count());
Response.Redirect(pageUrl + "?CategoryAction=remove");
}