Mahmoude Elghandour
Mahmoude Elghandour

Reputation: 2931

how to get value of the texbox inside loop in asp.net using C#?

I have 4 textboxes all of them take id "Ans" and number from 1 to 4

 <asp:TextBox ID="Ans1" runat="server" placeholder="Favorite Color"></asp:TextBox>

I have this loop to get value for each text box

        for(int i = 1 ; i<5 ; i++)
    {

        TextBox ans = FindControl (string.Concat("Ans", i.ToString()) as TextBox  != null );
    }

but i get this message "can not convert type string to textbox "

i don't know what wrong

Upvotes: 1

Views: 1070

Answers (3)

andrewb
andrewb

Reputation: 3095

Try this:

TextBox ans = (TextBox)FindControl(string.Concat("Ans", i.ToString()));
if(ans != null)
{
    // found the textbox
}

Upvotes: 2

drz
drz

Reputation: 992

For starters, you are missing a close paren )

I think this is what you mean

for(int i = 1 ; i<5 ; i++)
{
    TextBox ans = FindControl(string.Concat("Ans", i.ToString())) as TextBox;
}

Upvotes: 4

Claudio Redi
Claudio Redi

Reputation: 68440

You're missing a )

FindControl(string.Concat("Ans", i.ToString()))

I imagine it could be more readable like this

TextBox ans = FindControl(string.Format("Ans{0}",i)) as TextBox

Also, you need to remove != null at the end as, whatever you're trying to do, that's not the correct place :)

Upvotes: 3

Related Questions