Click here to Skip to main content
15,887,485 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
i try to create dynamic text box and get the data from this textboxes and its successfully if i put the number of textboxes that i need in the C# code

but if i created textbox to receive the repeated number from the user i have an error told me Input string was not in a correct format.

this my code with fixed number in the code
C#
protected void Page_PreInit(object sender, EventArgs e) { List keys = Request.Form.AllKeys.Where(key => key.Contains("txtDynamic")).ToList(); int i = 1; foreach (string key in keys) { this.CreateTextBox("txtDynamic" + i); i++; } }

protected void AddTextBox(object sender, EventArgs e)
{
    int index = pnlTextBoxes.Controls.OfType<TextBox>().ToList().Count + 1;
    this.CreateTextBox("txtDynamic" + index);
}

private void CreateTextBox(string id)
{

        TextBox txt = new TextBox();
        txt.ID = id;
        pnlTextBoxes.Controls.Add(txt);

        Literal lt = new Literal();
        lt.Text = "<br />";
        pnlTextBoxes.Controls.Add(lt);

}

protected void GetTextBoxValues(object sender, EventArgs e)
{
    string message = "";
    foreach (TextBox textBox in pnlTextBoxes.Controls.OfType<TextBox>())
    {
        message += textBox.ID + ": " + textBox.Text + "\\n";
    }
    ClientScript.RegisterClientScriptBlock(this.GetType(), "alert", "alert('" + message + "');", true);
}

this is my change to receive the number of textboxes from the user
C#
private void CreateTextBox(string id) { int x = Convert.ToInt32(txtNum.Text); for (int i = 0; i < x; i++) { TextBox txt = new TextBox(); txt.ID = id; pnlTextBoxes.Controls.Add(txt);

        Literal lt = new Literal();
        lt.Text = "<br />";
        pnlTextBoxes.Controls.Add(lt);
    }
}

please advice
Posted
Updated 26-Jul-15 2:11am
v2
Comments
[no name] 26-Jul-15 8:08am    
The error message means exactly what it says. It cannot convert txtNum.Text to a number because it's not a number.
jyo.net 27-Jul-15 2:14am    
Check the proper type casting is there or not.
Member 10875212 27-Jul-15 3:45am    
so i convert the text to the number so how i can convert in this case
[no name] 27-Jul-15 7:29am    
Stop using Convert and start using TryParse.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900