views:

43

answers:

2

I have populated a list box using a Data-table.

In another method, I have to retrieve the data table from the list box.

Datatable dt = (DataTable)lstExample.DataSource;

Throws an error, that the Datatable dt is null

I am working on c# ASP.Net

A: 

remove the () from lstExample.DataSource()

vaitrafra
+2  A: 

If you are trying to do this on a Postback then the DataTable will no longer be there. You will need to save it in ViewState or Session if you want access to it on a Postback, or just hit the database again.

For example:

protected override Page_Load(object sender, EventArgs e)
{
    if( !IsPostBack)
    {
        DataTable tbl = GetData();
        lstData.DataSource = tbl;
        lstData.DataBind();

        // store in viewstate
        ViewState["data"] = tbl;
    }
}

protected void btnSave_Click(object sender, EventArgs e)
{
    DataTable tbl = (DataTable)ViewState["data"];
}
Dismissile
I highly discourage saving it to ViewState. And if you save it to Session, make sure to check that it is not null and re-load and re-insert into Session from your data-store as needed.
Stephen Swensen
Thank you.. I stored the datatable in a session..
Pavithra Jayakumar
It really depends on the amount of data and the type of session state you are using. For a small amount of records storing it in viewstate won't be that bad. If you are running in a farm and using SQL Session State...it might make sense to just hit the database again.
Dismissile
Consider using the Cache for some kinds of data too. If the data table is populated with a rarely-changing list of codes, then you may not need to requery for each user.
Bill
@Dismissle: true points, except ViewState can grow out of control so easily, even just for serializing state of controls in your page, that I've learned it's best to aggressively minimize its use.
Stephen Swensen