I have a GridView and I populate it via a List . One of its columns is a DropDownList and AllowPaging is set to true. My problem is when I choose a value on the ddl and after a paging the selected value is lost. Is there any way/idea to persist the selected values? Thanks for your help.
2 Answers
You could use a Dictionary object within view state to save multiple values i.e.
Dictionary<int, string> ddlValues = new Dictionary<int, string>()
where int is the row index and string is the ddl selected value. Of course this could be an int/guid or whatever depending on the actual value stored in the ddl or an int if you want to work with selectedIndex instead.
on the page event you would need to do
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);
}
}
}
}
Don't worry about the current page ddl values. These will be persisted with viewstate in the normal way. It is the 'hidden' pages that we are accounting for. Hence we are repopulating the dictionary when the grid pages.
The Dictionary could then be saved in session/viewState and used to rehydrate the dropdownlist by doing the process in reverse. For instance when the page loads (checking !isPostBack
) or when the grid rebinds depending on exactly how you have set things up

- 9,300
- 8
- 34
- 62

- 6,219
- 8
- 38
- 73
-
I'm getting the values in dictionary but how to repopulate the same value in dropdownlist.. I have asked a **[Question here..!](http://stackoverflow.com/questions/22830180/persisting-dropdownlist-value-in-pageindexchanged-of-gridview)** Please help me – Amarnath Balasubramanian Apr 04 '14 at 06:39
You will probably want to persist the Data in the ViewState
. Check out this MSDN article
http://msdn.microsoft.com/en-us/library/ms972976.aspx
After you save it in the ViewState, you can retrieve the data on PostBack
like this:
if (!Page.IsPostBack)
{
//do some stuff
}
else
{
//retrieve the viewstate information
selectedValue= ViewState["dropdownlistValue"].ToString();
}
Alternatively, you could also maintain the information in a Session
variable but that may introduce other issues depending on what exactly you are doing.

- 4,811
- 11
- 41
- 67
-
Thank you Rondel for your reply. To save in the ViewState actually it's a good way, but my problem is I have to persist more than a value, i don't know how to do this. My grid view has a checkbox column to allow the selection of multiple rows at a time, that's why I need to persist many value. do you have any idea? – Bes-m M-bes Dec 11 '11 at 17:06