Pavithra Jayakumar
Pavithra Jayakumar

Reputation: 179

How to get a datatable from a listbox

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

Upvotes: 1

Views: 1886

Answers (1)

Dismissile
Dismissile

Reputation: 33071

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"];
}

Upvotes: 2

Related Questions