Search code examples
c#asp.netlistboxdatatable

How to bind a ListBox to a DataTable from a session object?


I have a session object that contains a DataTable from my previous page, and i would like to bind this DataTable to a ListBox.

I've done this:

protected void Page_Load(object sender, EventArgs e)
{
    if (!IsPostBack)
    {
        if (Session["bestStocks"] !=null)
        {
            DataTable dt = new DataTable();
           

            dt = (DataTable)Session["bestStocks"];

            DataView dv = new DataView(dt);
            BestStockslb.DataSource = dt;
            BestStockslb.DataBind();
        }
     }
 }

I get this result:

enter image description here

Any suggestion?


Solution

  • It seems you have forgot the DataTextField and DataValueField

     dt = (DataTable)Session["bestStocks"];
    
    DataView dv = new DataView(dt);
    BestStockslb.DataSource = dt;
    BestStockslb.DataTextField =  "Name";
    BestStockslb.DataValueField =  "ID"; 
    BestStockslb.DataBind();