Mental Jetsam

By Peter Finch

Archive for June, 2011

Accessing DataSource values from within a DataList ItemTemplate

Posted by pcfinch on June 29, 2011

The following C# (ASP.NET) code example shows a couple of ways to access the values returned by a asp:SqlDataSource from within a asp:DataList asp:ItemTemplate. The difficult part was accessing the data sources values and passing them to nested ASP controls like asp:Buttons and asp:ImageButtons.

<asp:SqlDataSource ID="ds" runat="server"
  ConnectionString="<%$ ConnectionStrings:portal %>"
  SelectCommand="select did, title, did from documents">
</asp:SqlDataSource>
<asp:DataList ID="dl" runat="server" DataSourceID="ds">
  <ItemTemplate>
    <div class="result">
      <a href='details.aspx?id=<%#Eval("did")%>>
      <div class="title"><%#Eval("title")%></div>
      <asp:ImageButton ID="butDelete" runat="server"
        ToolTip="Delete"
        ImageUrl="images/delete.png"
        OnClick="butDelete_Click"
        OnClientClick="javascript:confirm('Block comment thread?')"
        CommandName="delete"
        CommandArgument='<%# DataBinder.Eval(Container, "DataItem.did") %>' />
    </div>
  </ItemTemplate>
</asp:DataList>

In order to response to a click on one of the dynamically generated delete buttons use the following code.

protected void butDelete_Click (object sender, ImageClickEventArgs e)
{
  String command = ((ImageButton)sender).CommandName;
  if ("delete" == command) {
    int dId = Int16.Parse(((ImageButton)sender).CommandArgument);
    using(portalConnection portal = new PortalConnection())
    {
      portal.Delete(dId);
    }
    dl.DataBind();
  }
}

Posted in C#.NET | Leave a Comment »