2

我正在使用Entity FrameworkASPX 网络表单。在我的(GV) 中,我使用和GridView制作我的所有专栏。在编辑模式下,我可以选择一个新值,但它不会更新记录。在 GV 中,我将 a设置为与该字段的相关表匹配的 a。我需要哪些步骤,需要处理哪些事件?我已经尝试了and事件,但到目前为止还没有有用的代码。如果你想让我给你看一些糟糕的代码 - 只要问,我也会很高兴。我只需要一些关于接线的指导。ItemTemplatesEditTemplatesDropDownListEntityDataSourceRowEditingRowUpdating

4

1 回答 1

0

假设我有一个名为 customerEntities 的 ADO.NET 实体数据模型,它有一个表 Customers 和 3 列:

  1. 客户ID
  2. 姓名

ASPX:

<asp:GridView ID="gvCustomers" runat="server" AutoGenerateEditButton="true" 
    AutoGenerateColumns="false" onrowcancelingedit="gvCustomers_RowCancelingEdit" 
    onrowediting="gvCustomers_RowEditing" onrowupdating="gvCustomers_RowUpdating" DataKeyNames="CustomerId">
    <Columns>
        <asp:TemplateField>
            <ItemTemplate>
                <asp:Label ID="lblId" runat="server" Text='<%# Bind("CustomerId") %>' />
                <asp:Label ID="lblName" runat="server" Text='<%# Bind("Name") %>' />
                <asp:Label ID="lblSurname" runat="server" Text='<%# Bind("Surname") %>' />
            </ItemTemplate>
            <EditItemTemplate>
                <asp:TextBox ID="txtName" runat="server" Text='<%# Bind("Name") %>' />
                <asp:TextBox ID="txtSurname" runat="server" Text='<%# Bind("Surname") %>' />
            </EditItemTemplate>
        </asp:TemplateField>
    </Columns>
</asp:GridView>

后面的代码:

  protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
                BindCustomers();
        }

        private void BindCustomers()
        {
            customerEntities entityModel = new customerEntities();
            gvCustomers.DataSource = entityModel.Customers;
            gvCustomers.DataBind();
        }

        protected void gvCustomers_RowEditing(object sender, GridViewEditEventArgs e)
        {
            gvCustomers.EditIndex = e.NewEditIndex;
            BindCustomers();
        }

        protected void gvCustomers_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)
        {
            gvCustomers.EditIndex = -1;
            BindCustomers();
        }

        protected void gvCustomers_RowUpdating(object sender, GridViewUpdateEventArgs e)
        {
            int customerId = (int)gvCustomers.DataKeys[e.RowIndex].Value;
            TextBox txtName = (TextBox)gvCustomers.Rows[e.RowIndex].FindControl("txtName");
            TextBox txtSurname = (TextBox)gvCustomers.Rows[e.RowIndex].FindControl("txtSurname");

            customerEntities entityModel = new customerEntities();
            Customer customer = entityModel.Customers.Where(c => c.CustomerId == customerId).First();
            customer.Name = txtName.Text;
            customer.Surname = txtSurname.Text;
            entityModel.SaveChanges();

            gvCustomers.EditIndex = -1;
            BindCustomers();
        }
于 2013-01-26T05:00:13.740 回答