ASP.NET: Access ListView's DataSource object programatically

2.4k views Asked by At

I have bound my ListView to a database. I've used SqlDataSource to do the work. I want to change the datasource programatically but this is where it all goes wrong. I try to get the current datasource by doing so:

SqlDataSource oldSource = lstContacts.DataSource as SqlDataSource;

Then I want to save the SelectCommand of the SqlDataSource in a string:

string oldSelectCommand = oldSource.SelectCommand;

I am doing this because I want to check if the select statement contains an order by clause and if it does, to take it away and change it with another order by clause :)

However, I am getting this:

"System.NullReferenceException: Object reference not set to an instance of an object."

Anyone? Please (:

1

There are 1 answers

1
afzalulh On BEST ANSWER

This happens when you set ListView's DataSourceID in the markup like below:

<asp:ListView ID="ListView1" runat="server" 
    DataKeyNames="AccountID" DataSourceID="SqlDataSource1" >

The property DataSource is null if the binding comes by the DataSourceID property.

If you databind the ListView in your code, you can access them until there's any postback.ListView DataSource is not stored in viewstate, so it is lost until you set the datasource and rebind the ListView again.

Workaround: In the given scenario I would use a hidden field to store Order By clause, and set datasource of the ListView in code:

<asp:HiddenField ID="hdnOrderBy" runat="server" />
    <asp:ListView ID="ListView1" runat="server" DataKeyNames="AccountID">
        ... ... ...

And in the code:

private void BindListView()
{
    string orderBy = hdnOrderBy.Value;
    //Your conditions here
    if (orderBy.Contains("By AccountID"))
    {
        orderBy = " Order By CompanyName";
        hdnOrderBy.Value = orderBy;
    }

    string selectCommand = "SELECT [AccountID], [CompanyName], [CompanyID]  FROM [Account] ";
    SqlDataSource1.SelectCommand = String.Format("{0} {1}",selectCommand,orderBy);
    ListView1.DataSource = SqlDataSource1;
    ListView1.DataBind();
}

Hope it helps!