Reputation: 343
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..
Upvotes: 3
Views: 1378
Reputation: 62290
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;
}
Upvotes: 3
Reputation: 29036
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
, 002
and 003
the label will display the output as 001-002-003
Upvotes: 1