1

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

1 Answer 1

1

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!

1
  • Thanks for the answer! This is what I did: I stored the last select command in the ViewState collection and every time the selected item changed event occurs on the sort dropdown, I get the select command, modify it and then bind the list again :) everything works fine now :) Commented Sep 3, 2013 at 0:09

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.