How to bind a ListBox to a DataTable from a sessio

2019-05-11 13:32发布

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'v 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?

thanks, liron

2条回答
爷的心禁止访问
2楼-- · 2019-05-11 13:56

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();
查看更多
劳资没心,怎么记你
3楼-- · 2019-05-11 14:01

Change this line:

BestStockslb.DataSource = dt;

To:

BestStockslb.DataSource = dt.DefaultView;

And you also need to set the DataTextField and DataValueField Properties of BestStockslb to link to the required fields in the returned data. This is why you are getting the DataRowView output.

You could also remove DataView dv = new DataView(dt); as it looks like you are not using it.

查看更多
登录 后发表回答