如何在ascx页面中获取文本框值

本文关键字:获取 取文本 ascx | 更新日期: 2023-09-27 18:15:44

在我的项目中,我有3个用户控件,这些控件显示在母版页中。当我在文本框中输入值时,它不会得到当前值,它会显示以前的值。代码:

第一个数据绑定:

  protected void dlFirstZone_ItemDataBound(object sender, DataListItemEventArgs e)
  {
    if (((e.Item.ItemType == ListItemType.Item) || (e.Item.ItemType == ListItemType.AlternatingItem)) && (e.Item.DataItem != null))
    {
        using (GroceriesServiceClient groceriesServiceClient = new GroceriesServiceClient())
        {
            HomeMaster pp = (HomeMaster)e.Item.DataItem;
            int prdItem = pp.ProductId;
            ShoppingCart shopingCartParameter = new ShoppingCart();
            //if (pp.DisplayOrder == 1)
            //{
            Products products = new Products();
            if (basePage.BasePageWebSession != null)
            {
                shopingCartParameter.UserId = Convert.ToInt32(basePage.BasePageWebSession.UserId);
                cartlist = groceriesServiceClient.ShoppingCart_UserProductsList(shopingCartParameter);
                var td = (from c in cartlist
                          where c.ProductId == prdItem
                          select c);
                if (td.ToList().Count > 0)
                {
                   TextBox txtQtyDataview = (TextBox)e.Item.FindControl("txtQty");
                   txtQtyDataview.Text = td.First().Quantity.ToString();
                }
            }
            //}
            //else 
        }
    }
}

2nd ItemCommand事件处理程序:

protected void dlProduct_ItemCommand(object source, DataListCommandEventArgs e)
{
   HomeMaster q = (HomeMaster)e.Item.DataItem;
   if (e.CommandName == "AddToCart")
   {
      using (GroceriesServiceClient gsc = new GroceriesServiceClient())
      {
         ShoppingCart shoppingcart = new ShoppingCart();
         shoppingcart.UserId = basePage.BasePageWebSession.UserId;
         shoppingcart.UserName = basePage.BasePageWebSession.UserName;
         shoppingcart.ProductId = Convert.ToInt32(Convert.ToInt32(dlProductDataView.DataKeys[e.Item.ItemIndex]));
         TextBox tb1 = (TextBox)e.Item.FindControl("txtQty");
         if (!string.IsNullOrEmpty(tb1.Text))
            shoppingcart.Quantity = Convert.ToInt32(tb1.Text);
         else
            shoppingcart.Quantity = 1;
            shoppingcart = gsc.ShoppingCart_InsertOrUpdate(shoppingcart);
            Response.Redirect(Request.RawUrl);    
      } 
   }
}

如何在ascx页面中获取文本框值

您可以使用findControl来查找用户控件中的文本框,如下所示(假设在名为uc1的用户控件中有一个名为tb1的文本框:

 me.uc1.findControl("tb1").text
但是,更好的方法是公开一个可调用的公共函数来返回值:

在UserControl中创建公共函数:

public function getValue() as string
       return me.tb1.text
   end Function

然后您可以从任何具有对用户控件的引用的页面或控件访问它:

dim whatsMyName as string = me.uc1.getValue()