Search code examples
c#asp.netwinformsdatalist

Dynamic Values In DataList As A Label


I am trying to update a label on a button click in a data list. However I can't seem to figure out how to select each value that shows up, So if I hit the button on the 3rd item in the list it should show that value in a Label1 or if I click on the 5th item it should show that as the Label1. I can only pull values from directly grabbing them like DataList1.Items[0].FindControl. How do I get the value from each individual item in the list on a button click. (I also added a text box in an attempt to fill that as well) Below is my code:`

<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 />



`

Here is the 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)
{

}

}


Solution

  • Add CommandName="Selected" property to button and use it in ItemCommand event like:

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