DataList 中的动态值作为标签

Dynamic Values In DataList As A Label

我正在尝试更新数据列表中单击按钮时的标签。但是我似乎无法弄清楚如何 select 每个显示的值,所以如果我点击列表中第 3 个项目的按钮,它应该在 Label1 中显示该值,或者如果我点击第 5 个item 它应该显示为 Label1。我只能从直接获取值中提取值,例如 DataList1.Items[0].FindControl。如何通过单击按钮从列表中的每个单独项目中获取值。 (我还添加了一个文本框来尝试填充它)下面是我的代码:`

<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
    <asp:ListBox ID="ListBox1" runat="server"></asp:ListBox>
    <asp:DataList ID="DataList1" runat="server" DataKeyField="TempID" DataSourceID="SqlDataSource1">
        <ItemTemplate>
            User:
            <asp:Label ID="UserLabel" runat="server" Text='<%# Eval("User") %>' />
            <br />
            Time:
            <asp:Label ID="TimeLabel" runat="server" Text='<%# Eval("Time") %>' />
            <br />
            ActualTime:
            <asp:Label ID="ActualTimeLabel" runat="server" Text='<%# Eval("ActualTime") %>' />
            <br />
            TempID:
            <asp:Label ID="Label2" runat="server" Text='<%# Eval("TempID") %>' />
            <br />



`

下面是代码:

 protected void Page_Load(object sender, EventArgs e)
{

}
void BindList()
{
    DataList1.DataSource = DataList1;
    DataList1.DataBind();
}
public void DataList1_ItemCommand(object source, DataListCommandEventArgs e)
{
    DataList1.SelectedIndex = e.Item.ItemIndex;
    BindList();
    Label1.Text = "You selected: " +
                  ((Label)DataList1.SelectedItem.FindControl("ActualTimeLabel")).Text;
}
protected void Button1_Click(object sender, EventArgs e)
{

    int count = DataList1.Items.Count;
    for (int i = 0; i < count; i++)
    {
        Label lbl = DataList1.Items[0].FindControl("ActualTimeLabel") as Label;
        string labeltext = lbl.Text;

        TextBox1.Text = labeltext;
    }
}


protected void Button2_Click(object sender, EventArgs e)
{

}

}

CommandName="Selected" 属性 添加到按钮并在 ItemCommand 事件中使用它,例如:

public void DataList1_ItemCommand(object source, DataListCommandEventArgs e)
{
    if(e.CommandName == "Selected")
    {
         Label lbl = e.item.FinControl("ActualTimeLabel") as Label;
         Label1.Text = "You selected: " + lbl.Text;
    }
}