Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/templates/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何在asp.net中绑定数据列表模板字段_Asp.net_Templates_Bind_Datalist - Fatal编程技术网

如何在asp.net中绑定数据列表模板字段

如何在asp.net中绑定数据列表模板字段,asp.net,templates,bind,datalist,Asp.net,Templates,Bind,Datalist,我想将我在Datalist模板中创建的标签绑定到数据源中名为“item”的列 经过几次尝试后,我使用了以下代码 DataList2.DataSource = dt; // my DataSource Label l1 = (Label)DataList2.FindControl("itemLabel"); l1.Text = dt.Rows[0]["item"].ToString(); DataList2.DataBind();

我想将我在Datalist模板中创建的标签绑定到数据源中名为“item”的列

经过几次尝试后,我使用了以下代码

        DataList2.DataSource = dt;  // my DataSource
        Label l1 = (Label)DataList2.FindControl("itemLabel");
        l1.Text = dt.Rows[0]["item"].ToString();
        DataList2.DataBind();
我在第“3”行遇到以下错误我正在寻找正确的表达式

Object reference not set to an instance of an object.

任何帮助都将不胜感激。

标签为空,因为它是
NamingConainer
(用于
FindControl
)不是
DataList
,而是它的
DataListItems
之一(一个
DataList
用于多个项目)

因此,首先需要
DataBind
it,然后才能处理它的事件。在那里,您可以找到标签和底层的
DataItem

void Item_Bound(Object sender, DataListItemEventArgs e)
{
   if (e.Item.ItemType == ListItemType.Item || 
       e.Item.ItemType == ListItemType.AlternatingItem)
   {

    // Retrieve the Label control in the current DataListItem.
    Label itemLabel= (Label)e.Item.FindControl("itemLabel");
    DataRow row = ((DataRowView)e.Item.DataItem).Row;
    String item = row.Field<string>("item");
    itemLabel.Text = item;
 }
}
void Item\u绑定(对象发送方,DataListItemEventArgs e)
{
如果(e.Item.ItemType==ListItemType.Item ||
e、 Item.ItemType==ListItemType.AlternatingItem)
{
//检索当前DataListItem中的Label控件。
Label itemlab=(Label)e.Item.FindControl(“itemlab”);
DataRow row=((DataRowView)e.Item.DataItem).row;
字符串项=行字段(“项”);
itemLabel.Text=项目;
}
}

可能发生两种情况。标签为空或数据表为空。哪一个?我们可以使用类似foreach(Datalist2.items中的DataListItem)的东西吗?如果问题是多个项目,那么就进行绑定,但是我尝试了,但是代码表达式不正确。您也可以
DataBind
数据列表
foreach
之后的项目:
foreach(DataList2.Items中的DataListItem项){}
。但是我会使用
ItemDataBound
,原因有两个。它将确保在数据绑定时始终执行代码,并且它是有效的,因为循环不是额外的循环(
item\u Bound
将为每个项调用)。