Mike Hughes
Mike Hughes

Reputation: 77

How to hide all text boxes if they are empty

I'm just wondering really. I have series of if statements that check

if textboxes are empty (or have results strings) after i pass SQL results to then

.

if (IncidentData.Tables[0].Rows[0]["Property Category"].ToString() 
                                                     == "RoadVehicle") 
{ 
   lbl_alarmOperated.Visible = false; tb_alarmOperated.Visible = false; 
} 
else 
{ 
   lbl_alarmOperated.Visible = true;
   tb_alarmOperated.Visible = true; 
}

I have been looking into controls and seeing if i can do a check on all textboxes and hide them if they are empty (instead of writing loads of if statements)

i have this at the moment:

public void ChecknHide()
{
    HideTextBoxes(this);
}

protected void HideTextBoxes(Control ctrl)
{
    foreach (var c in ctrl.Controls)
    {
        if (c is TextBox) ((TextBox)c).Text = String.Empty;
        {
            ((TextBox)c).Visible = false;
        }
    }        
}

Its mostly put together from reading posts on here. But I've ran into an issue. When i compile and go to view the page i get this:

Unable to cast object of type 'ASP.masterpage_master' to type 'System.Web.UI.WebControls.TextBox'.

Any ideas whats going wrong?

Upvotes: 1

Views: 1260

Answers (3)

Max
Max

Reputation: 13386

Weird code line:

if (c is TextBox) ((TextBox)c).Text = String.Empty;

Try something like:

protected void HideTextBoxes(Control ctrl)
{
    //Iterate over controlls
    foreach (var c in ctrl.Controls)
    {
        //Check for Textbox controls with the .Text property equal to Null or Empty.
        if (c is TextBox && string.IsNullOrEmpty(((TextBox)c).Text))
        {
            //Set visibility of Textbox control to invisible.
            ((TextBox)c).Visible = false;
        }
    }
}

Upvotes: 0

Kurt Sample
Kurt Sample

Reputation: 1

You're checking if c is a TextBox, but then trying to cast c as a TextBox and set it to String.Empty in the same line, regardless of whether it actually is a TextBox.

if (c is TextBox) ((TextBox)c).Text = String.Empty;

Upvotes: 0

Arjen
Arjen

Reputation: 5333

The statement after the if isn't part of the condition. This causes all controls to be casted to a TextBox. You should be able to fix it like so:

protected void HideTextBoxes(Control ctrl)
{
    foreach (var c in ctrl.Controls)
    {
        if (c is TextBox && ((TextBox)c).Text == String.Empty)
        {
            ((TextBox)c).Visible = false;
        }

    }


}

Upvotes: 1

Related Questions