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

末鹿安然 提交于 2019-12-10 10:08:53

问题


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:

Any suggestion?

thanks, liron


回答1:


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();



回答2:


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.



来源:https://stackoverflow.com/questions/8803859/how-to-bind-a-listbox-to-a-datatable-from-a-session-object

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!