fanle
fanle

Reputation: 7

C# validation error

Hey I'm pretty new to c# and I'm sure that this isn't too difficult of an issue, however I cannot get my head around it.

I have a method in which I retrieve all of the variables from a windows form and submits them into another method that inserts them into the database. It works fine when the variables are declared however when I try and add in a bit of validation to check for null values I am recieveing a "the name 'gridRef1V' does not exist in the current context" error.

The validation I have at the minute is,

if (cbGridRef1.SelectedValue != null)
        {
            string gridRef1V = cbGridRef1.SelectedValue.ToString();
        }
        else
        {
            MessageBox.Show("The grid ref1 field must contain a value");
            cbGridRef1.Focus();
        }

The line of code that is recieveing the error message is,

SQLMethods.inspectionInsert(scrapTypeV, scrapShiftV, scrapDateV, prodAreaV, castDateV, dieNoV, dieCodeV, dieDescV, machineV, casterIDV, castShiftV, fettlerIDV, scrapCodeV, scrapTotalV, partIDV, gridRef1V, gridRef2V, qtyScrapV);

Thanks for any help in advance.

Upvotes: 0

Views: 184

Answers (2)

Mike Christensen
Mike Christensen

Reputation: 91666

Try:

string gridRef1V;
if (cbGridRef1.SelectedValue != null)
        {
            gridRef1V = cbGridRef1.SelectedValue.ToString();
        }
        else
        {
            MessageBox.Show("The grid ref1 field must contain a value");
            cbGridRef1.Focus();
        }

You have to declare gridRef1V outside the scope of that if block to use it elsewhere.

Upvotes: 0

sclarson
sclarson

Reputation: 4422

You have a scope error. Move

string gridRef1V;

To outside of the if statement.

When you have it inside the if statement, the variable is not available outside of that code block.

    // gridRef1v doesn't exist
    if (cbGridRef1.SelectedValue != null)
    {
        string gridRef1V = cbGridRef1.SelectedValue.ToString();
    }  //gridRef1V no longer available after this } 
    else
    {
        // gridRef1v doesn't exist
        MessageBox.Show("The grid ref1 field must contain a value");
        cbGridRef1.Focus();
    }
    // gridRef1v doesn't exist

What you want is something more like:

    string gridRef1v;
    if (cbGridRef1.SelectedValue != null)
    {
       gridRef1V = cbGridRef1.SelectedValue.ToString();
    }  //gridRef1V still available after this } 
    else
    {
        // gridRef1v exists
        MessageBox.Show("The grid ref1 field must contain a value");
        cbGridRef1.Focus();
    }
    // gridRef1v exists

Upvotes: 2

Related Questions