简体   繁体   中英

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 ?

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;
 }

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;
       }
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM