Click here to Skip to main content
12,248,978 members (34,989 online)
Rate this:
 
Please Sign up or sign in to vote.
See more: C# .NET C#4.0 .NET4
Here is my code...this code generate Error....so help me.

public void ShowHideControl(Control control)
        {
            TextBox tb = control as TextBox;
            tb.Enabled = false;
            ComboBox cb = control as ComboBox;
            cb.Enabled = false;
            if (control.HasChildren)
            {
                foreach (Control child in control.Controls)
                {
                    ClearControl(child);
                }
            }
        }


Error message is "nullreferenceexception was unhandled " and "Object reference not set to an instance of an object."
Posted 26-Dec-12 21:08pm
Edited 26-Dec-12 21:16pm
v2
Comments
   
In what line?
—SA
   
I see. And what, you did not use the debugger? Please, always execute the code under debugger and learn what happens before asking such questions. This kind of exception is the easiest one to detect and fix.

—SA
Shambhoo kumar 27-Dec-12 6:55am
   
tb.Enabled = false;
Rate this: bad
 
good
Please Sign up or sign in to vote.

Solution 1

The operator as is a dynamic type cast: a type check and the cast at the same time. If the object is not of the checked type, it returns null. You should check the result for null and not use it (not dereference) if it is null.

It will solve the problem.

[EDIT]

Also, you code lacks recursion; in general case, the controls in question could be placed in some child controls as panels. Your could should not depend on that, so the recursive check of all controls is important.

—SA
  Permalink  
v2
Rate this: bad
 
good
Please Sign up or sign in to vote.

Solution 2

i solve my self by another process.....

 TextBox[] Txtarr=new TextBox[]{txtcustname,txtbilladd,txtshipadd,txtEmail,txtphone,txtMobile,txtFax,txtState,TxtCity};
public void ShowHideControl(TextBox[] tbArray,int x)
       {
           for (int i = 0; i < tbArray.Length; i++)
           {
               if (x == 0)
               {
                   tbArray[i].Enabled = false;
               }
               else
               {
                   tbArray[i].Enabled = true;
               }
           }
       }
  Permalink  

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

  Print Answers RSS
Top Experts
Last 24hrsThis month


Advertise | Privacy | Mobile
Web01 | 2.8.160426.1 | Last Updated 28 Dec 2012
Copyright © CodeProject, 1999-2016
All Rights Reserved. Terms of Service
Layout: fixed | fluid

CodeProject, 503-250 Ferrand Drive Toronto Ontario, M3C 3G8 Canada +1 416-849-8900 x 100