Here i am using one example to show you how i am preserving the selected values of DropDownList and ListBox using Disctionary and ViewState. I am having three season values in DropDownList and ListBox contains Season fruites. On Button Click i am storing these values in ViewSate
HTML:
<form id="form1" runat="server">
<div>
<asp:DropDownList ID="ddlSeasons" runat="server">
<asp:ListItem Text="Summer" Value="0" />
<asp:ListItem Text="Winter" Value="1" />
<asp:ListItem Text="Rainy" Value="2" />
</asp:DropDownList>
<asp:ListBox ID="lbFruites" runat="server">
<asp:ListItem Text="Mango" Value="0" />
<asp:ListItem Text="Apple" Value="1" />
<asp:ListItem Text="Banana" Value="2" />
<asp:ListItem Text="Orange" Value="2" />
</asp:ListBox>
<asp:Button runat="server" OnClick="Save" Text="Save" />
</div>
</form>
C#:
protected void Save(object sender, EventArgs e)
{
if (ViewState["SelectedValues"] == null)
{
Dictionary<string, string> dictionary = new Dictionary<string, string>();
dictionary.Add(this.ddlSeasons.SelectedItem.Text, this.lbFruites.SelectedItem.Text);
ViewState["SelectedValues"] = dictionary;
}
else
{
Dictionary<string, string> dictionary = (Dictionary<string, string>)ViewState["SelectedValues"];
dictionary.Add(this.ddlSeasons.SelectedItem.Text, this.lbFruites.SelectedItem.Text);
ViewState["SelectedValues"] = dictionary;
}
}
Image:
first i have selected Summer and Mango the i select Winter and apple so i am storing these values in Dictionary.
Thank You.