Click here to Skip to main content
Sign Up to vote bad
good
See more: 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 - 20:08
Edited 26 Dec '12 - 20:16

Comments
Sergey Alexandrovich Kryukov - 27 Dec '12 - 2:10
In what line? —SA
Sergey Alexandrovich Kryukov - 27 Dec '12 - 2:14
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:55
tb.Enabled = false;

2 solutions

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

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

  Print Answers RSS
Your Filters
Interested
Ignored
     
0 OriginalGriff 300
1 Slacker007 240
2 Aarti Meswania 210
3 Ron Beyer 200
4 Mahesh Bailwal 186
0 Sergey Alexandrovich Kryukov 8,598
1 OriginalGriff 7,024
2 CPallini 3,668
3 Rohan Leuva 3,011
4 Maciej Los 2,343


Advertise | Privacy | Mobile
Web04 | 2.6.130516.1 | Last Updated 28 Dec 2012
Copyright © CodeProject, 1999-2013
All Rights Reserved. Terms of Use
Layout: fixed | fluid