在分页上保留下拉列表

时间:2011-12-11 16:35:09

标签: asp.net gridview

我有一个GridView,我通过List填充它。其中一列是DropDownList,AllowPaging设置为true。我的问题是当我在ddl上选择一个值时,在分页之后,所选的值就会丢失。是否有任何方法/想法来坚持选定的值? 谢谢你的帮助。

2 个答案:

答案 0 :(得分:1)

您可以在视图状态下使用Dictionary对象来保存多个值,即

Dictionary<int, string> ddlValues = new Dictionary<int, string>()

其中int是行索引,string是ddl选择的值。当然,这可能是一个int / guid或其他任何东西,取决于存储在ddl中的实际值或int,如果你想使用selectedIndex代替。

您需要执行的页面事件

protected void MyGridView_PageIndexChanging(Object sender, GridViewPageEventArgs e)
{
   for(int rowIndex = 0; rowIndex < myGridView.Rows.Length; rowIndex++)
   {
        DropdownList ddl = myGridView.Rows[rowIndex].FindControl("ddlId") as DropDownList

    if(ddl != null)
        {
           if(ddl.SelectedIndex > 0) //.. or sensible check appropriate to you
           {
               int ddlIndex = rowIndex * e.NewPageIndex + 1;

               //.. add pageIndex and selectedValue to dictionary
               ddlValues.Add(ddlIndex, ddl.SelectedValue);

            }

        }
    }
}

不要担心当前页面的ddl值。这些将以正常方式与viewstate持久存在。这是我们正在考虑的“隐藏”页面。因此,我们在网格页面时重新填充字典。

然后可以将词典保存在session / viewState中,并通过反向执行该过程来重新水化下拉列表。例如,当页面加载(检查!isPostBack)或网格重新绑定时,具体取决于您的设置方式

答案 1 :(得分:0)

您可能希望在ViewState中保留数据。查看此MSDN文章

http://msdn.microsoft.com/en-us/library/ms972976.aspx

将其保存在ViewState中后,您可以检索PostBack上的数据,如下所示:

 if (!Page.IsPostBack)
        {
           //do some stuff
        }
        else
        {
            //retrieve the viewstate information
                selectedValue= ViewState["dropdownlistValue"].ToString();

        }

或者,您也可以将信息保存在Session变量中,但这可能会引入其他问题,具体取决于您的具体操作。

相关问题