CAN I LOOP THROUGH TEXTBOX ID’S TO CHECK VALUES IN ASP.NET

Pravesh Singh

Total Post:412

Points:2888
Posted by  Pravesh Singh
C#  Loop 
 943  View(s)
Ratings:
Rate this:

I'm working on a project and I'm a beginner and I'm having a little trouble with this. I'm trying to check if a textbox is empty and if it is to change the value to N/A so that I can input n/a into a database instead of it not working.

Here is the code that I thought would work but didn't because the .Text property isn't near the ID anymore:

for(int i = 1; i<=17; i++)

{

if(!("tb" + i).Text)

"tb" + i.Text = "n/a";

}

I wasn't sure if the true/false would work but I never got to find out because it doesn't compile to begin with. I have 17 textboxes on my design page all with ID 'tb + i' e.g tb1, tb2

  1. Samuel Fernandes

    Post:159

    Points:1117
    Re: Can I loop through textbox id’s to check values in asp.net

    If you want to loop through the textbox ids, you have to find the control on the page first using the FindControl method.

    Then you can create your loop like this:

    TextBox txt;

    for(int i = 1; i<=17; i++)

    {

        txt = (TextBox)Page.FindControl("tb" + i);

        if(string.IsNullOrEmpty(txt.Text))

            txt.Text = "n/a";

    }

Answer

NEWSLETTER

Enter your email address here always to be updated. We promise not to spam!