Click here to Skip to main content
15,887,683 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
Dear Friends

I want to make a sub routine with some optional controls like Textbox and combobox. My sample sub routine is as under;

VB
Private Sub ActivateControls(rd As RadioButton, Optional  txt As TextBox)


End Sub


But when I wrote this sub routine Vb.Net IDE gives me the error that each Optional Parameter must specify a default value. So, here I cant understand that what can be the default value of a textbox.

If any body can help me, I will be grateful.

By

Rashid Farooq
Posted
Comments
William Winner 27-Jul-10 15:03pm    
Reason for my vote of 1
pretty basic google search

Optional arguments do need to be initialized so you could set it to Nothing.
VB
Private Sub ActivateControls(rd As RadioButton, Optional  txt As TextBox = Nothing)


End Sub
 
Share this answer
 
 
Share this answer
 
Thanks for Answering Brother.
Your answer does work.
But when I make a the subroutine with a default value of Nothing and when I run the program it runs correctly only if i gave all the arguments including optional values. If i miss only one optional argument it gives the error that Object Reference not set to an instance of object.
Here is my subroutine.
VB
Private Sub ActivateControls(rd As RadioButton, Optional  txt As TextBox = Nothing, txt2 As TextBox = Nothing)
End Sub


When I called this subroutine in my program as
ActivateControls(rdbtn,txt)


It gives me the following error

"Object Reference not set to an Instance of an Object"

But when I write this subroutine as
ActivateControls(rdbtn,txt,txt2)

It works right.

So, Please tell me what is the solution of this problem.

OR

Is there any other value Except Nothing That I can set as Default value of Optional controls(like textbox, combobox)
 
Share this answer
 
v2
Comments
[no name] 28-Jul-10 9:50am    
Well, it works for me. Are you sure that txt and txt2 are TextBoxes on your form? I've tried it both as a straight subroutine and as a class method and they both work. Are you sure it's supported in your version of .NET? I'm on VB 2010.
[no name] 28-Jul-10 9:53am    
Oh, I've just seen something. You need to have Optional as the last argument. Try changing it or making txt2 optional as well.
William Winner 28-Jul-10 12:44pm    
You also need to check to see if the object is nothing before trying to use it. I would guess you're code is something like this:

Private Sub ActivateControls(rd As RadioButton, Optional txt As TextBox = Nothing, txt2 As TextBox = Nothing)
If txt2.Text <> "" Then
'do something
End If
End Sub

If you do that or try to access txt2 or txt anywhere in your routine without first running

If txt2 IsNot Nothing Then ...

you'll get that error.

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



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900