Saturday 15 September 2012

c# - Dynamically created controls lose values -


ASP.NET 4.0 I want to allow users to view / edit items on a customer's license. There are 1-M products in a license, and the list of products will expand over time, so I have to say whether this product is in a license, such as: by creating a list of all products (in Page_load) P>

  checkbox cbxProduct = new checkbox (); CbxProduct.ID = "cbxProduct" + product.ID.ToString ();   

I can find those dynamic controls and use them on postback using them are:

  Czech box cbxprod = (box) pnlLicenseDetails. FindControl ("cbxProduct" + productID .tar ());   

but only if they are redone in Page_load (or Page_Init, does not matter). The problem is that I want the user to be able to uncheck a box to remove a product from the license and then save the result. But to find the checkbox and to determine its value, I will have to regenerate the control, which definitely erases any value entered by the user.

If I try to reference the checkbox without rebuilding them, I definitely get an "Object Reference not set ..." error. So I need some methods to get the values ​​before ending user input.

Suggestions?

You need to create them in the same way for all requests, you'll need to create dynamic control Page_Init. This means, to create control, run the same code and add it every time the page is loading, regardless of whether the IsPostBack is in the control collection.

In addition to this, I would recommend that you control a dynamic member variable so that you have to call FindControl , as it is probably expensive.

Since it seems that you have a list of products somewhere, here's one example, use a dictionary to store the checkbox:

  public Partial Class _Default: Pages {Private Dictionary & lt; Int32, checkbox & gt; _myDynamicCheckBoxes; Safe Override Zero OnInit (EventArgs e) {_myDynamicCheckBoxes = New Dictionary & lt; Int32, checkbox & gt; (); Foreign Currency (different products in _listOfProducts) {var chkBox = new checkbox {id = "checkbox" + product. ID ToString ()}; _myDynamicCheckBoxes.Add (product.ID, chkBox); // Add a checkbox for a control collection}}}   

Then somewhere in your code, when you have a product and you use the checkbox you want to associate with Can: var aCheckBox = _myDynamicCheckBoxes [product.ID];

No comments:

Post a Comment