DataList中的动态值作为标签

时间:2017-08-28 12:10:40

标签: c# asp.net winforms datalist

我正在尝试更新数据列表中按钮单击的标签。但是我似乎无法弄清楚如何选择显示的每个值,所以如果我点击列表中第3项的按钮,它应该在Label1中显示该值,或者如果我点击第5项它应该显示为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 />


                                                  
                                     `

以下是Code Behind:

 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)
{

}

}

1 个答案:

答案 0 :(得分:1)

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;
    }
}