标签在数据列表中返回空值
本文关键字:返回 空值 列表 数据 标签 | 更新日期: 2023-09-27 18:14:15
我有一个数据列表,一个标签,一个文本框和一个按钮。在一个按钮上单击我想要的文本框和标签的值,我得到文本框的值,但标签是空的。如何解决这个问题。Thanyou
protected void btnAdd_Click(object sender, EventArgs e)
{
foreach (DataListItem item in rptrItems.Items)
{
string quantity = ((TextBox)item.FindControl("txtQuantity")).Text;
string itemName =((Label)item.FindControl("itemName")).Text;
}
}
<asp:DataList ID="rptrItems" runat="server" RepeatColumns="3" >
<ItemTemplate>
<div class="panel panel-info">
<div class="panel-heading"> Item= <asp:Label ID="itemName" runat="server"> <strong>"<%#Eval("ItemName")%>"</strong></asp:Label></div>
<div class="panel-body">
<div class="row">
<label class="lblQuantity"> Quantity: </label>
<asp:TextBox ID="txtQuantity" runat="server" CssClass="form-control"></asp:TextBox>
</div>
<div class="row">
<asp:Button ID="btnAdd" runat="server" CssClass="btn-Add" OnClick="btnAdd_Click" /> </div>
</div>
</div>
</ItemTemplate>
</asp:DataList>
每个Canavar注释使用隐藏字段
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
rptrItems.DataSource = new List<Item>
{
new Item {ItemName = "Item Name",Quantity=1}
};
rptrItems.DataBind();
}
}
protected void btnAdd_Click(object sender, EventArgs e)
{
foreach (DataListItem item in rptrItems.Items)
{
string quantity = ((TextBox)item.FindControl("txtQuantity")).Text;
string itemName = ((HiddenField)item.FindControl("itemName")).Value;
}
}
public class Item
{
public string ItemName { get; set; }
public int Quantity { get; set; }
}
<asp:DataList runat="server" ID="rptrItems">
<ItemTemplate>
<asp:HiddenField ID="itemName" runat="server" Value='<%# Eval("ItemName") %>' />
<asp:Label ID="labItemName" runat="server" Text='<%# Eval("ItemName") %>' /> :
<asp:TextBox ID="txtQuantity" runat="server" Text='<%# Eval("Quantity") %>'></asp:TextBox>
</ItemTemplate>
</asp:DataList>
<asp:Button ID="btnSubmit" OnClick="btnAdd_Click" runat="server" Text="Submit" />
只有表单元素将它们的值发送给服务器,所以标签不发送它们的值。这就是为什么你不能得到它的Text值。试试隐藏输入元素。
看一下这里的HiddenField元素:
<asp:DataList ID="rptrItems" runat="server" RepeatColumns="3" >
<ItemTemplate>
<div class="panel panel-info">
<div class="panel-heading">
Item= <asp:Label ID="itemName" runat="server"> <strong>"<%#Eval("ItemName")%>"</strong></asp:Label>
<asp:HiddenField ID="itemName" runat="server" Value='<%# Eval("ItemName") %>' />
</div>
<div class="panel-body">
<div class="row">
<label class="lblQuantity"> Quantity: </label>
<asp:TextBox ID="txtQuantity" runat="server" CssClass="form-control"></asp:TextBox>
</div>
<div class="row">
<asp:Button ID="btnAdd" runat="server" CssClass="btn-Add" OnClick="btnAdd_Click" /> </div>
</div>
</div>
</ItemTemplate>
</asp:DataList>
在后面的代码中像这样访问它:
protected void btnAdd_Click(object sender, EventArgs e)
{
foreach (DataListItem item in rptrItems.Items)
{
string quantity = ((TextBox)item.FindControl("txtQuantity")).Text;
string itemName =((HiddenField)item.FindControl("itemName")).Value;
}
}