title: asp.net ListView Sorting using DataBind
body: <p><strong>Sort listview using column headings in the LayoutTemplate</strong></p>
  
  <p>I am able to sort a basic list view using asp:SqlDataSource and setting the list view property DataSourceID by pointing it to the asp:SqlDataSource ID.  I am having an issue when sorting when not using the asp:SqlDataSource and just DataBinding from the code behind.</p>
  
  <p><strong>SqlDataSource  Example:</strong></p>
  
  <pre><code>&lt;asp:ListView ID="ContactsListView" DataSourceID="ContactsDataSource" runat="server"&gt;
      &lt;LayoutTemplate&gt;
          &lt;table width="640px" runat="server"&gt;
              &lt;tr class="header" align="center" runat="server"&gt;
                  &lt;td&gt;
                      &lt;asp:LinkButton runat="server" ID="SortByFirstNameButton" CommandName="Sort" Text="First Name" CommandArgument="FirstName" /&gt;
      &lt;/LayoutTemplate&gt;
      ....
  &lt;/asp:ListView&gt;
  
  &lt;asp:SqlDataSource ID="ContactsDataSource" runat="server" 
      ConnectionString="&lt;%$ ConnectionStrings:MainConnString %&gt;"
      SelectCommand="SELECT * FROM TableName"&gt;
  &lt;/asp:SqlDataSource&gt;
  </code></pre>
  
  <p><strong>DataBind Example:</strong></p>
  
  <pre><code>&lt;asp:ListView ID="ContactsListView" DataSourceID="ContactsDataSource" runat="server"&gt;
      &lt;LayoutTemplate&gt;
          &lt;table width="640px" runat="server"&gt;
              &lt;tr class="header" align="center" runat="server"&gt;
                  &lt;td&gt;
                      &lt;asp:LinkButton runat="server" ID="SortByFirstNameButton" CommandName="Sort" Text="First Name" CommandArgument="FirstName" /&gt;
      &lt;/LayoutTemplate&gt;
      ....
  &lt;/asp:ListView&gt;
  
  protected void Page_Load(object sender, EventArgs e)
  {
      String SQL = "SELECT * FROM Customer";
      SqlDataAdapter da= new SqlDataAdapter(SQL, ConnStr);
      DataSet ds = new DataSet();
      da.Fill(ds);
  
      ContactsListView.DataSource = ds.Tables[0];
      ContactsListView.DataBind();
  }
  </code></pre>
  
  <p>Both code samples populate the list view, but the second example data binding does not work for sorting.  With the first example, the sorting just works with the added asp:LinkButton in the LayoutTemplate adding the CommandName="sort" and setting the CommandArugment="ColumnName", but it does not work with the second example.</p>
  
  <p>Can anyone please explain why and how to get the sorting working using the code behind DataBind method?</p>
  
  <p>Thanks!</p>