如何从会话对象将ListBox绑定到DataTable?
我有一个会话对象,其中包含我上一页的DataTable,我想将此DataTable绑定到ListBox。
我这样做了:
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(); } } }
我得到这个结果:
有什么建议吗?
谢谢,liron
您似乎忘记了DataTextField和DataValueField
dt = (DataTable)Session["bestStocks"]; DataView dv = new DataView(dt); BestStockslb.DataSource = dt; BestStockslb.DataTextField = "Name"; BestStockslb.DataValueField = "ID"; BestStockslb.DataBind();
改变这一行:
BestStockslb.DataSource = dt;
至:
BestStockslb.DataSource = dt.DefaultView;
您还需要设置BestStockslb的DataTextField和DataValueField属性以链接到返回数据中的必需字段。 这就是您获取DataRowView输出的原因。
你也可以删除DataView dv = new DataView(dt);
因为看起来你没有使用它。