Gridview绑定意外清除

时间:2012-12-30 14:29:34

标签: c# asp.net data-binding gridview

我的gridview有问题。我已经搜索了很多解决方案,但找不到任何答案。我想我找到的问题是,当我按下更新按钮时,gridview不再受限 - 这会导致空值。我认为在RowEditing绑定就足够了。我还能在哪里绑定我的gridview?

请参阅下面的标记:

    <asp:GridView ID="ProductGridView" runat="server" AllowPaging="True" AllowSorting="True"
    AutoGenerateColumns="False" DataKeyNames="Id" OnRowEditing="ProductGridView_RowEditing"
    OnRowCancelingEdit="ProductGridView_RowCancelingEdit" OnRowUpdating="ProductGridView_RowUpdating"
    OnRowDeleting="ProductGridView_RowDeleting" OnDataBound="ProductGridView_DataBound" OnRowDataBound="ProductGridView_RowDataBound">
    <Columns>
        <asp:CommandField ShowDeleteButton="True" ShowEditButton="True" CausesValidation="false" />
        <asp:TemplateField HeaderText="Name" SortExpression="Name">
            <EditItemTemplate>
                <asp:TextBox ID="txtName" runat="server" Text='<%# Bind("Name") %>'></asp:TextBox>
            </EditItemTemplate>
            <ItemTemplate>
                <asp:Label ID="lblName" runat="server" Text='<%# Eval("Name") %>'></asp:Label>
            </ItemTemplate>
        </asp:TemplateField>
        <asp:TemplateField HeaderText="Quantity" SortExpression="Quantity">
            <EditItemTemplate>
                <asp:TextBox ID="txtQuantity" runat="server" Text='<%# Bind("Quantity") %>'></asp:TextBox>
            </EditItemTemplate>
            <ItemTemplate>
                <asp:Label ID="lblQuantity" runat="server" Text='<%# Eval("Quantity") %>'></asp:Label>
            </ItemTemplate>
        </asp:TemplateField>
        <asp:TemplateField HeaderText="Family" SortExpression="Family.Name">
            <EditItemTemplate>
                <asp:DropDownList ID="ddlFamily" runat="server" OnInit="ddlFamily_Init">
                </asp:DropDownList>
            </EditItemTemplate>
            <ItemTemplate>
                <asp:Label ID="lblFamily" runat="server" Text='<%# Eval("Family.Name") %>'></asp:Label>
            </ItemTemplate>
        </asp:TemplateField>
    </Columns>
</asp:GridView>

代码隐藏:

    protected void Page_Load(object sender, EventArgs e)
    {
        if (!Page.IsPostBack)
        {
            BindGridView(_productRepo.GetAll());
        }
    }

    private void BindGridView(object source)
    {
        ProductGridView.DataSource = source;
        ProductGridView.DataBind();
    }

    protected void ProductGridView_RowEditing(object sender, GridViewEditEventArgs e)
    {
        ProductGridView.EditIndex = e.NewEditIndex;
        BindGridView(_productRepo.GetAll()); // GetAll returns an IEnumerable.
        rowCount = ProductGridView.Rows.Count; // Count is 6 here, which is correct.
    }

    protected void ProductGridView_RowUpdating(object sender, GridViewUpdateEventArgs e)
    {
        rowCount = ProductGridView.Rows.Count; // Count is 0 here.
        //BindGridView(_productRepo.GetAll()); // Tried to rebind which works but getting the old values obviously. 
        //rowCount = ProductGridView.Rows.Count; // Count is 6 here.

        // Get the controls - all is null. Works ok when I use BindGridView above.
        TextBox txtName = FindChildControl<TextBox>(this.Page, "txtName");
        TextBox txtQuantity = FindChildControl<TextBox>(this.Page, "txtQuantity");
        DropDownList ddlFamily = FindChildControl<DropDownList>(this.Page, "ddlFamily");

        // More code to populate a new product and bind the gridview again etc.
    }

我也有一个RowDataBound方法。这会导致这个问题吗?

protected void ProductGridView_RowDataBound(object sender, GridViewRowEventArgs e)
    {
        if (e.Row.RowType == DataControlRowType.DataRow && (e.Row.RowState & DataControlRowState.Edit) == DataControlRowState.Edit)
        {
            DropDownList ddl = (DropDownList)e.Row.FindControl("ddlFamily");
            ddl.DataSource = _familyRepo.GetAll().Select(f => f.Name);
            ddl.DataBind();
            Product product = _productRepo.FindSingle(p => p.Id == (int)ProductGridView.DataKeys[e.Row.RowIndex].Value);
            ddl.SelectedIndex = (int)product.FamilyID - 1;
        }
    }

3 个答案:

答案 0 :(得分:0)

如果我理解正确,您说数据网格中的表单控件在回发后会消失或重置为初始状态。

发生这种情况的原因是因为您在Page_Load方法中绑定了网格,这在页面生命周期中来不及恢复控件值。在触发LoadViewstate和LoadPostbackData事件之后,您的网格才会加载,因此,每次回发时,网格的控件都会以其原始状态加载。

我猜你已经熟悉了asp.net的生命周期,但如果没有这篇文章:http://msdn.microsoft.com/en-us/library/ms972976.aspx。我已经多次处理过这个问题了,我花了一些时间才完全理解这里发生了什么。

该问题的一个解决方案是在重写的OnInit方法中加载网格,该方法在恢复控制数据之前发生。这样的事情应该有效:

protected override void OnInit(EventArgs e)
{
    base.OnInit(e);
    BindGridView(_productRepo.GetAll());
}

答案 1 :(得分:0)

我通常以这种方式进行数据绑定....尝试使用此函数并在页面加载和其他需要的函数中调用它。

protected void bind()
{
    con.Open();
    SqlCommand cmd = new SqlCommand("Your Query", con);
    DataSet ds = new DataSet();
    SqlDataAdapter da = new SqlDataAdapter();
    da.SelectCommand = cmd;

    da.Fill(ds);

    gvCourse.DataSource = ds;
    gvCourse.DataBind();

    con.Close();

}

答案 2 :(得分:0)

或者你可以简单地用!IsPostBack

替换!Page.IsPostBack
protected void Page_Load(object sender, EventArgs e)
{
    if (!IsPostBack)
    {
        BindGridView(_productRepo.GetAll());
    }
}