Tartar
Tartar

Reputation: 5452

ASP.NET accessing value of the textboxes inside of the repeater

I want to check values of textboxes inside of a repeater. If all textboxes are empty i want to assign the check value to 0. I tried this implementation but i got this error System.InvalidCastException

            int check = 0;

            foreach (TextBox tb in searchResultRepeater.Items)
            {
             if(tb.Text == ""){
                check = 0;
             }else{
                check = 1;
             }
            }

How can i fix this exception ?

Upvotes: 0

Views: 1113

Answers (2)

Oleg Gryb
Oleg Gryb

Reputation: 5249

It means that not all object in Items collection are instances of TextBox. You need to run your loop with a tb defined as a more generic object and then check inside of the loop if tb is a TextBox

 foreach(RepeaterItem item in searchResultRepeater.Items){
    for (int i = 0; i < item.Controls.Count; i++) {
        Control ctrl = item.Controls[i];    
        if(ctrl is TextBox){
           TextBox tb = (TextBox) ctrl;
           if (tb.Text != null && tb.Text.Length > 0) {
                        check = 1;
                        break;
           }
        }
   }
   if (check == 1)
       break;
 }

Upvotes: 1

nizzik
nizzik

Reputation: 826

If your searchResultRepeter is an Repeater instead of looping though TextBoxes you should be using RepeaterItem. You can check if all of your items are acctualy the TextBox type.

    foreach(RepeaterItem item in searchResultRepeater.Items){
        if(item.Controls.Count > 0 && item.Controls[0] is ITextControl ) {
           if(((TextBox)item.Controls[0]).Text.IsNullOrEmpty()){
                check = 1;
                break;
       }
    }

Upvotes: 1

Related Questions