2011-10-10 41 views
0

嘿,我很新的C#,我敢肯定,這不是一個問題太難,但我無法讓我的頭。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(); 
     } 

的是recieveing錯誤消息代碼行,

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

感謝提前任何幫助。

+1

什麼是例外? –

+0

你在哪裏試圖使用'gridRef1V'?您正在將它聲明在塊中(在{}}之間(它是其存在的範圍),並且不能在塊之外使用它。 – Oded

+0

錯誤消息是,錯誤「gridRef1V」這個名字不會在目前情況下存在 – fanle

回答

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 
+0

感謝它擺脫了上下文的錯誤但是我現在越來越 錯誤使用未分配的局部變量「的gridRef1V '\t 指向Insert代碼的同一位。 – fanle

+0

沒關係,我給GridRef1V分配了一個初始值,並刪除了錯誤。再次感謝您的幫助 – fanle

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的那個範圍之外,如果塊在其他地方使用它。