如何从ListView获取价值

时间:2014-03-31 07:01:57

标签: c# asp.net listview

我有代码

<head>
    <title><%=txtTitle.Text</title>
</head> 

<asp:HiddenField ID="txtTitle" runat="server" />

<asp:ListView ID="lvDetNews" runat="server" DataSourceID="sdsBerita">
    <ItemTemplate>
        <asp:HiddenField ID="HFcari" runat="server" Value='<%# Eval("judul_berita") %>' />
        <h2><%# Eval("judul_berita") %></a></h2>            
    </ItemTemplate>
</asp:ListView>

如何从Listview获取值隐藏字段?

我正在尝试这个。但无法显示

protected void Page_Load(object sender, EventArgs e)
{
    HiddenField tt = (HiddenField)lvDetNews.FindControl("HFcari");
    txtTitle.Value = "tess" + tt;
}

3 个答案:

答案 0 :(得分:2)

protected void Page_Load(object sender, EventArgs e)
{
    HiddenField tt = (HiddenField)lvDetNews.FindControl("HFcari");
    txtTitle.Value = "tess" + tt.Value;
}

更新的 你得到了这个错误,因为listview还没有绑定,所以我认为最好的方法是在ItemDataBound事件上做所有这些。你会发现隐藏的字段如下:

  <asp:ListView ID="lvDetNews" runat="server" DataSourceID="sdsBerita"   OnItemDataBound="lvDetNews_ItemDataBound">
    <ItemTemplate>
        <asp:HiddenField ID="HFcari" runat="server" Value='<%# Eval("judul_berita") %>' />
        <h2><%# Eval("judul_berita") %></a></h2>            
    </ItemTemplate>
</asp:ListView>

protected void lvDetNews_ItemDataBound(object sender, ListViewItemEventArgs e)
{
    if (e.Item.ItemType == ListViewItemType.DataItem)
    {
         HiddenField tt = (HiddenField)e.Item.FindControl("HFcari");
          txtTitle.Value = "tess" + tt.Value;
    }
}

答案 1 :(得分:0)

您需要更改以下代码

protected void Page_Load(object sender, EventArgs e)
    {
        HiddenField tt = (HiddenField)lvDetNews.FindControl("HFcari");
        txtTitle.Value = "tess" + tt.Value;
    }

答案 2 :(得分:0)

如果您想获得页面加载值,您应该知道行号

var hiddenFld = this.lvDetNews.Items[<row_index>].FindControl("HFcari") as HiddenField;
string value = hiddenFld.Value();

否则你必须在ItemDataBound事件

中完成此操作
<head>
    <title><%=txtTitle.Text</title>
</head> 

<asp:HiddenField ID="txtTitle" runat="server" />

<asp:ListView ID="lvDetNews" runat="server" DataSourceID="sdsBerita"   OnItemDataBound="lvDetNews_ItemDataBound">
    <ItemTemplate>
        <asp:HiddenField ID="HFcari" runat="server" Value='<%# Eval("judul_berita")     %>' />
        <h2><%# Eval("judul_berita") %></a></h2>            
    </ItemTemplate>
</asp:ListView>

代码:

protected void lvDetNews_ItemDataBound(object sender, ListViewItemEventArgs e)
{
    if (e.Item.ItemType == ListViewItemType.DataItem)
    {
        var hiddenFld = e.Item.FindControl("HFcari") as HiddenFiled;
        string value = hiddenFld.Value();
        // ...
    }
}