c#验证错误
本文关键字:错误 验证 | 更新日期: 2023-09-27 18:10:48
嘿,我是c#新手,我相信这不是一个太难的问题,但是我无法理解它。
我有一个方法,在这个方法中,我从一个windows窗体中检索所有变量,并将它们提交到另一个方法中,该方法将它们插入到数据库中。当变量被声明时,它的工作很好,但是当我尝试添加一点验证来检查空值时,我收到一个"名称'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);
感谢您的帮助。
您有一个作用域错误。
移动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
尝试:
string gridRef1V;
if (cbGridRef1.SelectedValue != null)
{
gridRef1V = cbGridRef1.SelectedValue.ToString();
}
else
{
MessageBox.Show("The grid ref1 field must contain a value");
cbGridRef1.Focus();
}
你必须在if块的作用域之外声明gridRef1V才能在其他地方使用它