我在网上购物车项目中遇到了一个问题。。。。问题是当我获取/访问中继器控件内的文本框时。。。我在下面的代码中使用了这个,但当我在Textbox中输入一些值时,它会显示null值。。。。
代码背后:
protected void repeater1_ItemCommand(object source, RepeaterCommandEventArgs e)
{
if (e.CommandName == "addtoCartName")
{
foreach (RepeaterItem item in repeater1.Items)
{
TextBox txtName = (TextBox)item.FindControl("txtQuantity");
if (txtName!= null)
{
strText = strText + ", " + txtName.Text;
Response.Write("Text =" + strText);
}
}
}
aspx:
<asp:Button runat="server" ID="addtoCart" Text="Add to Cart" CommandName="addtoCartName" UseSubmitBehavior="false" />
文本框位置。。。
这里的c代码。。。
请务必回复感谢
我认为通过中继器控件进行循环是导致问题的原因,因为您不能确定它是否访问了正确行的文本框控件。您需要从引发事件的行中获取文本框:
protected void repeater1_ItemCommand(object source, RepeaterCommandEventArgs e)
{
if (e.CommandName == "addtoCartName")
{
TextBox txtName = (TextBox)e.Item.FindControl("txtQuantity")
if (txtName!= null)
{
strText = strText + ", " + txtName.Text;
Response.Write("Text =" + strText);
}
}
}
您在ListItem的ItemTemplate中有TextBox,而不是在页眉/页脚等中,所以您需要检查Repeater Item的Item Type。试试这个:
foreach (RepeaterItem item in repeater1.Items)
{
if (item.ItemType == ListItemType.Item || item.ItemType == ListItemType.AlternatingItem)
{
TextBox txtName = (TextBox)item.FindControl("txtQuantity");
if (txtName!= null)
{
strText = strText + ", " + txtName.Text;
Response.Write("Text =" + strText);
}
}
}