C# – Convert ‘Control’ to textbox and assign it a value

asp.netccontrols

I am trying to create a form. The form controls names are always going to be the same. However the type of control will change. For example, I have a control named "first_name". When the page is initialized, it retrieves data from a database stating what the type of control (TextBox, DropDownList or CheckBox); Then the form is dynamically created on the page. To keep the viewstate, I created the control in the OnInit method.

protected override void OnInit(EventArgs e)
{
    Control first_name;
    string ControlType = GridView1.Rows[0].Cells[1].Text;
    switch (ControlType)
    {
        case("TextBox"):
            first_name = new Control() as TextBox; first_name.ID = "first_name"; this.Controls.Add(first_name);
            break;
        case("DropDownList"):
            first_name = new Control() as DropDownList; first_name.ID = "first_name"; this.Controls.Add(first_name);
            break;
        case("CheckBox"):
            first_name = new Control() as CheckBox; first_name.ID = "first_name"; this.Controls.Add("first_name");
            break;
    }
}

Then I render the control to the page.

protected override void Render(HtmlTextWriter writer)
{
    writer.Write("first_name: ");
    first_name.RenderControl(writer);
}

Next, I try to assign values to the control. This is where I run into problems. I know that when it's declared globally, it is declared as a control and holds those values.

Is there a way to declare it globally from within a function or to change the type of a control after it's been declared globally?

protected void Page_Load(object sender, EventArgs e)
{
    switch (first_name.GetType().ToString())
    {
        case ("TextBox"):
            first_name.Text = "Your First Name...";
            break;
        case ("DropDownList"):
            first_name.Items.Add("Jason");
            first_name.Items.Add("Kelly");
            first_name.Items.Add("Keira");
            first_name.Items.Add("Sandi");
            first_name.Items.Add("Gary");
            break;
        case ("CheckBox"):
            first_name.Checked = true;
            break;
    }        
}

Please provide a way that I can accomplish this.

Best Answer

In your OnInit you should do new TextBox() and not new Control() as TextBox since the second will just return null.

Your Page_Load would be something like this:

if (first_name is TextBox)
    ((TextBox)first_name).Text = "Your First Name...";
else if (first_name is DropDownList)
{
    var drp = (DropDownList)first_name;
    drp.Items.Add();
    // ...
}