title: Asp.Net binding specific fields of sql query to Listview
body: <p>I have a listview that has a few different controls. I need to bind specific fields of a query to certain parts of a control. The table contains a friendid and a firstname. I want to put the friendid at the end of a URL. I want to put the firstname in the text of a label. There will be multiple friends returned on the query. The listview should show all in a separate row. Here is what I have, which is obviously not right.</p>
  
  <pre><code>&lt;asp:ListView ID="lvFriends" runat="server"&gt;
      &lt;LayoutTemplate&gt;
      &lt;ul ID="itemPlaceholderContainer" runat="server" style=""&gt;
          &lt;li ID="itemPlaceholder" runat="server" /&gt;
      &lt;/ul&gt;
  &lt;/LayoutTemplate&gt;
      &lt;ItemTemplate&gt;
          &lt;li&gt;
              &lt;div style="float:left;"&gt;
                  &lt;a id="A1" href='&lt;%# ResolveUrl(String.Format("~/UserPages/FriendsPages/FriendsProfile.aspx?friend={0}", Container.DataItem)) %&gt;' runat="server"&gt;&lt;asp:Image ID="ImageButton1" ImageUrl='&lt;%# ResolveUrl(String.Format("~/UserPages/FriendsPages/FriendsThumbImage.aspx?friend={0}", Container.DataItem)) %&gt;' runat="server" /&gt;&lt;/a&gt;
          &lt;/div&gt;
  
              &lt;div style="margin-left:300px;"&gt;
          &lt;ul&gt;
              &lt;li&gt;&lt;asp:Label ID="FirstNameLabel" runat="server" Text='&lt;%# Eval("FriendFN") %&gt;' /&gt;&lt;/li&gt;
          &lt;/ul&gt;
      &lt;/div&gt;
          &lt;/li&gt;
      &lt;div style="clear:both;"&gt;&lt;/div&gt;
      &lt;/ItemTemplate&gt;
  &lt;ItemSeparatorTemplate&gt;&lt;br /&gt;&lt;/ItemSeparatorTemplate&gt;
  &lt;/asp:ListView&gt;
  </code></pre>
  
  <p>CODE BEHIND:</p>
  
  <pre><code>string strCon = System.Web.Configuration.WebConfigurationManager.ConnectionStrings["SocialSiteConnectionString"].ConnectionString;
  using (SqlConnection conn = new SqlConnection(strCon))
  {
      using (SqlCommand cmd = conn.CreateCommand())
      {
          conn.Open();
          cmd.CommandText = "SELECT * from [Friends] WHERE [UserId] = @UserId";
          cmd.Parameters.AddWithValue("@UserId", User.Identity.Name);
  
          DataTable dtFriends = new DataTable();
          dtFriends.Columns.Add("FriendId");
          dtFriends.Columns.Add("FriendFN");
  
          SqlDataReader nwReader = cmd.ExecuteReader();
          while (nwReader.Read())
          {
              string RdFriendId = nwReader["FriendId"].ToString().ToLower();
              string RdFriendFN = nwReader["FriendFirstName"].ToString().ToLower();
  
              dtFriends.Rows.Add(new object[] {RdFriendId, RdFriendFN});
          }
          nwReader.Close();
          Session.Add("FriendsTable", dtFriends);
  
          conn.Close();
          lvFriends.DataSource = dtFriends;
          lvFriends.DataBind();
      }
  }
  </code></pre>