Bind (Populate) ASP.Net DropDownList in another page with Session using C# and VB.Net

Last Reply 9 days ago By pandeyism

Posted 9 days ago

How to store session value into a dropdown of another page?

You are viewing reply posted by: pandeyism 9 days ago.
Posted 9 days ago

Hi nid@patel,

Refer below sample.

HTML

CS.aspx

ID : <asp:TextBox runat="server" ID="txtId" />
<asp:Button Text="Redirect" runat="server" OnClick="Redirect" />

Default.aspx

<asp:DropDownList runat="server" ID="ddlCountries">
</asp:DropDownList>
<asp:DropDownList runat="server" ID="DropDownList1">
    <asp:ListItem Text="Select" Value="0" />
    <asp:ListItem Text="1" Value="1" />
    <asp:ListItem Text="2" Value="2" />
    <asp:ListItem Text="3" Value="3" />
</asp:DropDownList>

Namespaces

C#

using System.Data;

VB.Net

Imports System.Data

Code

CS.aspx.cs

protected void Redirect(object sender, EventArgs e)
{
    DataTable dt = new DataTable();
    dt.Columns.AddRange(new DataColumn[] { new DataColumn("Country", typeof(string)), new DataColumn("Id", typeof(int)) });
    dt.Rows.Add("USA", 1);
    dt.Rows.Add("India", 2);
    dt.Rows.Add("France", 3);
    Session["dt"] = dt;
    Session["Name"] = txtId.Text;
    Response.Redirect("Default.aspx");
}

Default.aspx.cs

protected void Page_Load(object sender, EventArgs e)
{
    if (!this.IsPostBack)
    {
        DataTable dt = Session["dt"] as DataTable;
        ddlCountries.DataSource = dt;
        ddlCountries.DataTextField = "Country";
        ddlCountries.DataValueField = "Id";
        ddlCountries.DataBind();
        ddlCountries.Items.Insert(0, new ListItem("Select", "0"));

        DropDownList1.ClearSelection();
        DropDownList1.Items.FindByText(Session["Name"].ToString()).Selected = true;
    }
}

VB.Net

VB.aspx.vb

Protected Sub Redirect(ByVal sender As Object, ByVal e As EventArgs)
    Dim dt As DataTable = New DataTable()
    dt.Columns.AddRange(New DataColumn() {New DataColumn("Country", GetType(String)), New DataColumn("Id", GetType(Integer))})
    dt.Rows.Add("USA", 1)
    dt.Rows.Add("India", 2)
    dt.Rows.Add("France", 3)
    Session("dt") = dt
    Session("Name") = txtId.Text
    Response.Redirect("Default.aspx")
End Sub

Default.aspx.vb

Protected Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs) Handles Me.Load
    If Not Me.IsPostBack Then
        Dim dt As DataTable = TryCast(Session("dt"), DataTable)
        ddlCountries.DataSource = dt
        ddlCountries.DataTextField = "Country"
        ddlCountries.DataValueField = "Id"
        ddlCountries.DataBind()
        ddlCountries.Items.Insert(0, New ListItem("Select", "0"))
        DropDownList1.ClearSelection()
        DropDownList1.Items.FindByText(Session("Name").ToString()).Selected = True
    End If
End Sub

Screenshot