views:

228

answers:

2

I have a datalist and would like to pull the row names from the table that I am getting my values from for the datalist. Heres an example of what I would like to do.

<HeaderTemplate>
    'Get data row names
'Maybe something like Container.DataItem(row)?
    </HeaderTemplate>
A: 

You could do the following, but I doubt it would work. I don't believe DataItems are available at the point when the Header is being created.

((DataRowView)Container.DataItem).DataView.Table.Columns

If this works, you can loop through this collection and inspect each item's ColumnName property.

A better idea would be to either:

  1. Create a property in codebehind that returns a List<string> of appropriate column headers. You can refer to this property in markup when you're declaring the header.
  2. Add a handler for the ItemDataBound event and trap header creation. You will still need a way to refer to the data elements, which probably haven't been prepped at this point.
David Andres
A: 

If you are using a DataTable as a Data Source for your Data List you could use the OnItemCreated method and provide a custom handler for the ItemCreated event to add the column header values. I'm not sure why you would want to do this. It sounds like a Repeater or GridView might be better suited to your needs. At any rate, here's the code.

<asp:DataList ID="DataList1" runat="server" OnItemCreated="DataList1_ItemCreated"
      ShowHeader="true" >
     <HeaderTemplate>
     </HeaderTemplate>
     </asp:DataList>

protected void Page_Load(object sender, EventArgs e)
    {  
        using (SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["LocalSqlServer"].ToString()))
        {
            conn.Open();
            SqlCommand comm = new SqlCommand("SELECT [id], [name], [email], [street], [city] FROM [employee_tbl]", conn);
            SqlDataAdapter da = new SqlDataAdapter(comm);
            da.Fill(dt);
        }
        DataList1.DataSource = dt;
        DataList1.DataBind();
    }

  protected void DataList1_ItemCreated(object sender, DataListItemEventArgs e)
    {
        if (e.Item.ItemType == ListItemType.Header)
        {
            foreach (DataColumn col in dt.Columns)
            {
                Literal lit = new Literal();
                lit.Text = col.ColumnName;
                e.Item.Controls.Add(lit);
            }
        }
    }
Phaedrus