How to avoid repeating code

B

Brian Lin

Hi all,

I have a table called Category and it has only two fields: CategoryID
and CategoryName. I want user to be able to enter 10 categories at one
page. So I what I do right now is to place 10 text input boxs on the
page with name txt1, txt2, txt3, etc. After the user submit. I will
check to see if each txt box is empty and insert into table if not.

The problem is that I need duplicate the code for each text box. I am
wondering if there is a way to just loop through those text boxes and do
the checking and inserting inside the loop. That would really cut down
the amount of codes.

I am new to asp.net, so please help :)

Thanks in advance,

Brian
 
G

Guest

Hi Brian,

There are a few ways to do this. One way is to create an ArrayList and add
all the TextBoxes to it. Then iterate through the Arraylist (foreach(TextBox
tb in objList)). The ArrayList is only holding references to the objects so
it is relatively lightweight.

Tim
 
S

Siva M

This is another way:

foreach (Control c in <form ID>.Controls)
{
if (c is TextBox)
{
if (((TextBox)c).Text.Length == 0)
{
Response.Write(c.ID + " is empty.");
return;
}
}
}

Hi all,

I have a table called Category and it has only two fields: CategoryID
and CategoryName. I want user to be able to enter 10 categories at one
page. So I what I do right now is to place 10 text input boxs on the
page with name txt1, txt2, txt3, etc. After the user submit. I will
check to see if each txt box is empty and insert into table if not.

The problem is that I need duplicate the code for each text box. I am
wondering if there is a way to just loop through those text boxes and do
the checking and inserting inside the loop. That would really cut down
the amount of codes.

I am new to asp.net, so please help :)

Thanks in advance,

Brian
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,767
Messages
2,569,572
Members
45,045
Latest member
DRCM

Latest Threads

Top