[英]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: 更好的主意是:
List<string>
of appropriate column headers. List<string>
。 You can refer to this property in markup when you're declaring the header. 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.
听起来Repeater或GridView可能更适合您的需求。 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.