Вопрос

ASP.NET 4.0. I want to allow users to view/edit items on a customer's license. A license has 1-M products, and the list of products will expand over time, so I'm dynamically creating a list of all products (in Page_Load) with a checkbox to say whether a license has that product, like this:

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

I can find those dynamic controls and access their values on PostBack using:

CheckBox cbxProd = (CheckBox)pnlLicenseDetails.FindControl("cbxProduct" + productID.ToString());

but only if they have just been re-created in Page_Load (or Page_Init, doesn't seem to 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 results. But in order to find the checkbox and determine its value, I have to re-create the controls, which of course erases any value the user entered.

If I try to reference the checkboxes without re-creating them, I of course get an "object reference not set..." error. So I need some way to capture the values the user inputs before they are wiped out.

Suggestions?

Это было полезно?

Решение

You have to create dynamic controls in Page_Init. You have to create them the same way for all requests. That means, run the same code to create the control and add it to the controls collection every time the page is loaded regardless of IsPostBack or not.

Also, I would suggest that you save the instance of the dynamic control to a private member variable so you don't have to call FindControl as that is potentially expensive.

Since it looks like you have a list of products somewhere, here is an example using a dictionary to store the checkboxes:

public partial class _Default : Page
{
    private Dictionary<Int32,CheckBox> _myDynamicCheckBoxes;

    protected override void OnInit(EventArgs e)
    {
        _myDynamicCheckBoxes = new Dictionary<Int32,CheckBox>();

        foreach (var product in _listOfProducts)
        {
            var chkBox = new CheckBox {ID = "CheckBox" + product.ID.ToString()};
            _myDynamicCheckBoxes.Add(product.ID,chkBox);
            //add the checkbox to a Controls collection
        }
    }
}

Then somewhere else in your code, when you have a product and you want to find the checkbox associated you can use: var aCheckBox = _myDynamicCheckBoxes[product.ID];

Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top