0

C#

protected void imgbtn5_Click(object sender, EventArgs e)
{
    Session["theme"] = lbl5.Text;
    foreach (ListViewItem item in theme5.Items)
    {
        Label country = (Label)item.FindControl("lblcountry");
        Session["country"] = country.ToString();        
        Label price = (Label)item.FindControl("lblprice");
        Session["price"] = price.ToString();         
    }       
}

这里因为 foreach 会话值再次变为空。请提出其他方法。

aspx

<asp:ListView ID="theme5" runat="server" DataSourceID="SqlDataSource5">
<ItemTemplate>
<asp:Label ID="lblcountry" runat="server" Text='<%#Eval("Country") %>' />
</ItemTemplate>
</asp:ListView>

在这里,我想获取我的标签文本值并将其传输到会话。我想有问题:

Label country = (Label)theme5.FindControl("lblcountry");

在这个国家,我在调试时发现空值。

4

3 回答 3

1

您正在添加标签而不是标签文本

protected void imgbtn5_Click(object sender, EventArgs e)
{
    Session["theme"] = lbl5.Text;
    foreach (ListViewItem item in theme5.Items)
    {
        Label country = (Label)item.FindControl("lblcountry");
// here insted of country.ToString() you Should use 
        Session["country"] = country.Text.ToString();        
        Label price = (Label)item.FindControl("lblprice");
        Session["price"] = price.Text.ToString();         
    }       
}
于 2012-09-17T12:38:12.650 回答
0

您可以尝试使用此代码

var index = ...;

var result = (label)theme5.Items[index].FindControl("lblcountry");

您可以使用此代码基于Itemcommand

<asp:ListView ID="theme5" runat="server" DataSourceID="SqlDataSource5">
    <ItemTemplate>
    <asp:Button ID="btn"
    Text="..."
    CommandName="YourCommand"
    CommandArgument='<%# Container.DataItemIndex %>'
    runat="server"   ItemCommand="Test_ItemCommand" />
    </ItemTemplate>
</asp:ListView>



protected void Test_ItemCommand(object sender, ListViewCommandEventArgs e)
{

 if (e.CommandName.Equals("YourCommand"))
 {
      var result = (label)theme5.Items[Convert.ToInt32(e.CommandArgument)].FindControl("lblcountry"); 
 }

}
于 2012-09-17T09:02:40.207 回答
0

我认为您需要访问theme5当前选定的项目并获取该项目中的标签:

Label lblcountry = 
  (Label)theme5.Items[theme5.SelectedIndex].FindControl("lblcountry");
于 2012-09-17T09:04:30.613 回答