Frage

I recently created a web user control in asp.net that represents a printer. The user control contains a checkbox that i use to set an IsChecked property:

    protected bool isChecked;

    /// <summary>
    /// Is printer selected
    /// </summary>
    public bool IsChecked
    {
        get { return isChecked; }
        set { isChecked = value; }
    }

    protected void chkIsSelected_CheckedChanged(object sender, EventArgs e)
    {
        if (isChecked)
        {
            isChecked = false;
        }
        else
        {
            isChecked = true;
        }
    }

I want to be able to select printers using the checkboxes (multiselection too) and use an "Add selected" button to add the selected "printers (user controls)".

  protected void btnSubmitSelection_Click(object sender, EventArgs e)
    {
        Dictionary<string, string> addResults = new Dictionary<string, string>();

        foreach (PrinterControlSearch pctrl in printerControls)
        {

            if (pctrl.IsChecked)
            {
                addResults.Add(pctrl.printer.PrinterName, PrinterOperations.addPrinter(client, pctrl.printer));
            }
        }
     }

All works fine if I add the web user controls in the Page_Init or Page_Load events. The CheckedChanged events are triggered one by one for each checked control after the postback from the AddSelected button in the main page is fired and the IsChecked property is set as it should for the checked checkboxes.

However if I add the web user controls to the page withing a method that is triggered by a postback from a search button for example, the controls are displayed ok, but the CheckedChanged events never trigger on the AddSelected postback and the IsChecked property is always false as it never gets set. The checkBox that I use doesn't cause an AutoPostBack.

Why does this happen and how can I make it work everytime?

I supose it's somehow related to the ViewState of the controls but it doesn't make much sense for me because even if I add the controls in the Page_Load event I dont't set any property after the container.AddControl() method for the ViewState to catch up with the page life cycle, and the CheckedChanged event still gets triggered. Thanks

War es hilfreich?

Lösung

You need to recreate dynamically created controls on every postback in page's load event at the latest.

That's required to trigger events and to correctly load the ViewState, otherwise the postback data is lost and you'll never see any changes(f.e. Checked-state of a CheckBox or Text property of a TextBox).

You can create controls dynamically in event handlers(later than page_load). But you need to recreate them in page load at the latest(better in page_init).

Loop through Dynamically Created Controls

Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top