3

I am getting posts in datalist. I would like to show post id but i coundn't perfectly..

I would like to get post id with hidden field, any idea?

I've tried on button click:

protected void post_button_Click(object sender, EventArgs e)
{
    HiddenField hiddenField = datalist1.Items[0].FindControl("hfield") as HiddenField;
    lbl_note.Text = Convert.ToString(hiddenField);
}

This is working but just for first hiddenfield because of Items[0], if you want to get second hiddenfiled than i can change Items[1].

But i would like to get those values to be automatically in datalist. (when i click the post's button)

I've tried foreach function but it get's last hidden field's value. So, i miss something but i'm not sure.

protected void post_button_Click(object sender, EventArgs e)
{
   foreach (DataListItem item in datalist1.Items)
   {
        var hidden_id = int.Parse(((HiddenField)item.FindControl("hfield")).Value); 
       lbl_note.Text = Convert.ToString(hidden_id);             
   }
}

Datalist1:

<asp:DataList ID="datalist1" runat="server">
   <ItemTemplate>                
        <div>       
            <asp:LinkButton ID="post_picture" runat="server" OnClick="post_picture_Click"><img src="~/testing.png" alt=""></asp:LinkButton>     
            <h3><asp:LinkButton ID="post_title" runat="server" OnClick="post_title_Click"><%# Eval("post_title")%></asp:LinkButton></h3>
            <asp:LinkButton runat="server" ID="post_button" OnClick="post_button_Click" >GO >></asp:LinkButton>
            <asp:HiddenField ID="hfield" runat="server" Value='<%# Eval("post_id")%>'  />
       </div>
   </ItemTemplate>
</asp:DataList>  

UPDATED..

sujith karivelil
  • 26,861
  • 6
  • 46
  • 76
Cagatay
  • 313
  • 1
  • 3
  • 12

2 Answers2

3

You want to get DataListItem first, and then find hfield.

protected void post_button_Click(object sender, EventArgs e)
{
    var button = sender as LinkButton;
    var dataListItem = button.Parent as DataListItem;
    var hfield = dataListItem.FindControl("hfield") as HiddenField;
    lbl_note.Text = hfield.Value;
}
Win
  • 56,078
  • 13
  • 92
  • 167
1

From the comment, you need to display all the id's of hidden fields in lbl_note so you have to use something like the following:

List<string> hdnIdList= new List<string>();
foreach (DataListItem item in datalist1.Items)
{
     hdnIdList.Add(((HiddenField)item.FindControl("hfield")).Value);                      
}
lbl_note.Text = String.Join("-",hdnIdList);  

Let the id's are 001, 002and 003 the label will display the output as 001-002-003

sujith karivelil
  • 26,861
  • 6
  • 46
  • 76
  • Well,i tried, there is no action.. I am not sure why.. Clicking on the post's button on the page but no error, no result.. @un-lucky – Cagatay Apr 27 '16 at 14:04