Pavitar
Pavitar

Reputation: 4384

Variable does not exist in current context and invalid arguments

enter image description here

I am trying to validate a text box.I have validated a couple of other text boxes and they work fine.This one has some error. My code looks correct to me.Someone please point out my mistake and tell me why Visual Studio 2010 is prompting an error of invalid arguments and variable not in current context:

Upvotes: 0

Views: 2395

Answers (7)

Nicola Musatti
Nicola Musatti

Reputation: 18236

You need to pass a string as second parameter to ValidAddress. Try and add

string errorMsg = null;

as first line of addTextBox_Validating()

Upvotes: 1

AlanT
AlanT

Reputation: 3663

As far as I can see, errorMsg is not declared anywhere.

Try changing addTextBox_Validating by adding a declaration for it

e.g.

var errorMsg = string.Empty;

if (!ValidAddress(...

An out variable needs to be declared in the context that it is used.

hth
Alan.

Upvotes: 0

Steven Jeuris
Steven Jeuris

Reputation: 19130

Read up on how to use out.

Although variables passed as an out arguments need not be initialized prior to being passed, the calling method is required to assign a value before the method returns.

class OutExample
{
    static void Method(out int i)
    {
        i = 44;
    }
    static void Main()
    {
        int value;
        Method(out value);
        // value is now 44
    }
}

Upvotes: 1

Owen
Owen

Reputation: 1561

Where is errorMsg defined? It looks like it's sent in as a parameter to ValidAddress, so addTextBox_Validating, being a different method entirely, doesn't have access to it, as errorMsg is scoped to only exist in ValidAddress. Long story short, you haven't initialised your variable.

Upvotes: -1

Mufaka
Mufaka

Reputation: 3444

You need to define the errorMsg variable before using it as an out parameter.

string errorMsg;

Upvotes: 1

BonyT
BonyT

Reputation: 10940

You have not declared the errorMsg string.

private void addTextBox_Validating (object sender, CancelEventArgs e)
{
    string errorMsg = "";
    ...etc

}

In ValidAddress, the errorMsg string is passed in to the function as a parameter, so this issue does not arise.

Upvotes: 0

Barry Kaye
Barry Kaye

Reputation: 7759

You need to define string errorMsg; in addTextBox_Validating function before you call ValidAddress.

Upvotes: 3

Related Questions