我在RowDatabound事件上设置的ASP.NET GridView数据在回发后丢失

时间:2011-10-14 21:19:58

标签: asp.net gridview postback viewstate

我有一个asp.net页面,我有一个gridview控件,它绑定DataTable中的数据。 在网格的第5列中,我显示了一个单选按钮列表,其中包含2个单选按钮项(是或否)。对于某些行,如果第4列单元格值为空,则不会显示RadioButton控件。它工作正常。但是在我的按钮单击事件(回发)中,网格显示最初未显示的那些单元格的单选按钮列表。我为页面启用了ViewState和Control

这是我的代码

<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns=false 
                             DataKeyNames="RequestDetailId" ondatabound="GridView1_DataBound"  EnableViewState ="true" AllowPaging=false
                             onrowdatabound="GridView1_RowDataBound">
       <Columns>
           <asp:BoundField DataField="RequestDetailId" HeaderText="Request Detail Id" />
           <asp:BoundField DataField="Item" HeaderText="Item" />
           <asp:BoundField DataField="Status" HeaderText="Status" />
           <asp:BoundField DataField="NewOffer" HeaderText="New Offer" />
           <asp:TemplateField HeaderText="Your Response" ItemStyle-CssClass="radioTD">
               <ItemTemplate>
                   <asp:RadioButtonList ID="radioList" runat="server">
                        <asp:ListItem Text="Yes" Value="Accept"></asp:ListItem>
                        <asp:ListItem Text="No" Value="Reject"></asp:ListItem>
                    </asp:RadioButtonList>

                 </ItemTemplate>
            </asp:TemplateField>
       </Columns>                    
 </asp:GridView>

中的代码

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

 private void LoadItemDetails()
 {
     DataTable objDt=  GetGridDataSource();
       if (objDt.Rows.Count > 0)
       {                     
                  GridView1.DataSource = objDt;
                  GridView1.DataBind(); 
        }
 }
 protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
 {          
        if(String.IsNullOrEmpty (e.Row.Cells[3].Text.Trim())||(e.Row.Cells [3].Text =="&nbsp;"))
        {
            e.Row.Cells[4].Text = "";   
        }
  }

我的结果是

回发前

enter image description here

回发后

enter image description here

如何在回发后维护内容?谢谢

2 个答案:

答案 0 :(得分:4)

问题是您将GridView表格单元格的Text设置为空字符串,而不是将RadioButtonList控件的可见性设置为false。

清除Text属性是在第一次加载时删除RadioButtonList的标记,但是在回发时不会触发RowDataBound事件,并且会重新创建并重新显示RadioButtonList控件。

为了避免这种情况,您可以找到控件并将其可见性设置为false,然后将在回发中记住这一点。

尝试以下方法:

protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
    if (String.IsNullOrEmpty(e.Row.Cells[3].Text.Trim()) || (e.Row.Cells[3].Text == "&nbsp;"))
    {
        RadioButtonList radioList = (RadioButtonList)e.Row.FindControl("radioList");
        radioList.Visible = false;
    }
}

希望这有帮助。

答案 1 :(得分:1)

你可以做这样的事情......

从问题的描述。听起来好像你正在后面的代码中进行数据绑定。在这种情况下,asp.net不会为您保留视图状态中的数据源。尝试检索数据并将其存储在ViewState散列表对象中,类似于

ViewState["GridviewData"] = GridviewData

并在回发之间从中回复

相关问题