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会话值再次变为null。 请提出其他建议。
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");
在国家/地区,我在dubugging时找到空值。
答案 0 :(得分: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();
}
}
答案 1 :(得分: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");
}
}
答案 2 :(得分:0)
我认为您需要访问当前所选的theme5项目并获取该项目中的标签:
Label lblcountry =
(Label)theme5.Items[theme5.SelectedIndex].FindControl("lblcountry");