1

I want to use FindControl to find the value of the HiddenField i.e hfBlogID. I want to find the value on a ButtonClick

<asp:ListView ID="lvArticle" runat="server">
    <LayoutTemplate>
        <div runat="server" id="itemPlaceHolder">
        </div>
    </LayoutTemplate>
    <ItemTemplate>
        <asp:HiddenField ID="hfBlogID" Value='<%#Eval("BlogID")%>' runat="server" />
        <p>
            <%#Eval("BlogTitle")%></p>
        <p>
            <%#Eval("BlogDetails")%></p>
    </ItemTemplate>
</asp:ListView>
4

4 回答 4

3

In order to determine the correct row index you should place your button inside of your ListView.ItemTemplate and handle the ListView.ItemCommand event.

In order to implement this approach you would have to change your code as follows:

<asp:ListView ID="lvArticle" runat="server" OnItemCommand="lv_ItemCommand">
..
    <ItemTemplate>
        <asp:HiddenField ID="hfBlogID" Value='<%#Eval("BlogID")%>' runat="server" />
        <p>
            <%#Eval("BlogTitle")%></p>
        <p>
            <%#Eval("BlogDetails")%></p>
        <asp:Button runat="server" CommandName="find" CommandArgument='<%# Eval("yourIDField") %>' />
    </ItemTemplate>
...

In code behind:

protected void lv_ItemCommand(object sender, ListViewCommandEventArgs e)
{
    switch (e.CommandName)
    {
        case "find":
            var hidden = e.Item.FindControl("your hidden id") as HiddenField;
            break;
    }
}

If your button is not inside your ListView, then you would need a way to identify the row you want to extract the hidden value from.

For example, if you allow to select a row in your ListView then you could get the hidden value from the selected row as follows:

protected void find_Click(object sender, EventArgs e)
{
    var hidden = this.lv.Items[this.lv.SelectedIndex].FindControl("your hidden ID") as HiddenField;
}
于 2012-07-27T09:01:54.327 回答
0

you can use if button is in your listview

var control = (HiddenField)e.Item.FindControl("hfBlogID");

or if button is not in your listvew

 var contorl = (HiddenField)this.lvArticle.Items[this.lvArticle.SelectedIndex].FindControl("hfBlogID");
于 2012-07-27T08:58:33.300 回答
0

If the button is in the same item template then use ItemCommand event handler and in that handler you can fetch the hidden field directly.

If the button is outside of list view then you need to get the index of item whose hidden field'd value you want to get.

于 2012-07-27T09:02:17.307 回答
0

Here you can access the hidden field for each item:

protected void Button1_Click(object sender,EventArgs e)
{
  foreach(ListViewDataItem item in lvArticle.Items)
   {
     HiddenField hf=(HiddenField)item.FindControl("hfBlogID");
   }

}

if you have index of item already then you can get it directly like this

 HiddenField hf=(HiddenField)lvArticle.Items[index].FindControl("hfBlogID");

Hope this will help..

于 2012-07-27T09:10:34.023 回答