简体   繁体   English

在数据列表中获取行名

[英]Getting Row's Name in a DataList

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>

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. 我不相信在创建标头时就可以使用DataItems。

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

If this works, you can loop through this collection and inspect each item's ColumnName property. 如果可行,则可以遍历此集合并检查每个项目的ColumnName属性。

A better idea would be to either: 更好的主意是:

  1. Create a property in codebehind that returns a List<string> of appropriate column headers. 在代码隐藏中创建一个属性,该属性返回适当列标题的List<string> 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. 为ItemDataBound事件添加一个处理程序,并创建陷阱标头。 You will still need a way to refer to the data elements, which probably haven't been prepped at this point. 您仍然需要一种方法来引用数据元素,这可能尚未准备好。

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. 如果将DataTable用作数据列表的数据源,则可以使用OnItemCreated方法,并为ItemCreated事件提供自定义处理程序,以添加列标题值。 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. 听起来RepeaterGridView可能更适合您的需求。 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);
            }
        }
    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM