Click here to Skip to main content
Rate this: bad
good
Please Sign up or sign in to vote.
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 21:08pm
Edited 26-Dec-12 21:16pm
v2
Comments
Sergey Alexandrovich Kryukov at 27-Dec-12 2:10am
   
In what line?
—SA
Sergey Alexandrovich Kryukov at 27-Dec-12 2:14am
   
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 at 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
0 Sergey Alexandrovich Kryukov 383
1 Sascha Lefévre 215
2 Maciej Los 185
3 Abhinav S 170
4 Richard Deeming 155
0 Sergey Alexandrovich Kryukov 7,141
1 OriginalGriff 6,410
2 Maciej Los 2,832
3 Abhinav S 2,732
4 Peter Leow 2,694


Advertise | Privacy | Mobile
Web03 | 2.8.150414.1 | Last Updated 28 Dec 2012
Copyright © CodeProject, 1999-2015
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