简体   繁体   中英

Accessing a control dynamically added to a placeholder during an event

I'm creating an ASP.NET control dynamically based on a value selected in a dropdown; for instance the field can be a textbox or a checkbox (for now), and then it gets added to a placeholder control. However, I'm unsure how to retrieve the value - using the placeholder's FindControl method returns null although I'm specifying the ID when I create the control.

Here's my code:

protected void ddlFields_SelectedIndexChanged(object sender, EventArgs e) {
    // this simply gives me back an object with some properties 
    // such as the type of field (e.g. text, boolean, number)
    var column = GetFieldDetailsByValue(ddlFields.SelectedValue);
    this.CreateInputControl(column.Type);  
}

private void CreateInputControl(string dataType) { 
    Control controlToAdd = null;

    switch (dataType) {
        case TYPE_STRING:
        case TYPE_NUMBER:
            controlToAdd = new TextBox();
            break;
        case TYPE_BOOL:
            controlToAdd = new CheckBox();
            break;      
    }

    if (controlToAdd != null) { 
        controlToAdd.ID = "ctlFieldValue";
        this.fieldsPlaceholder.Controls.Add(controlToAdd);
    }
}

I have a Button event which checks for the ctlFieldValue control to retrieve it's value, however it's always null. How should I go about handling this?

The only way you'll be able to retrieve the value during a postback is if you create the control collection the exact same way. So, if you're adding the control during an event, on the postback, you need to create the exact same control (with the same id) within the same parent control.

Unfortunately - that's kind of difficult to do when you're adding controls during postback events. What I have done in the past is use ViewState to keep track of which controls should be created during postbacks. There might be a better way to do this though, but doing the ViewState route seems to work.

您总是可以直接从Request.Form集合中读取过帐的值。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM