C#验证错误

时间:2011-10-10 15:25:50

标签: c# visual-studio validation scope

嘿,我对c#很陌生,我确信这不是一个问题,但是我无法理解它。

我有一个方法,我从窗体中检索所有变量,然后将它们提交到另一个将它们插入数据库的方法中。它在声明变量时工作正常,但是当我尝试添加一些验证以检查空值时,我接收到“当前上下文中不存在名称'gridRef1V'”错误。

我现在的验证是,

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

收到错误消息的代码行是

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

感谢您提前提供任何帮助。

2 个答案:

答案 0 :(得分:2)

您有范围错误。移动

string gridRef1V;

在if语句之外。

当你在if语句中使用它时,该变量在该代码块之外是不可用的。

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

你想要的更像是:

    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

答案 1 :(得分:0)

尝试:

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

你必须将gridRef1V声明在if块的范围之外,以便在别处使用它。