2014-05-19 37 views
0

下面是我的跟蹤志願者的計劃。我的問題是,在下面的兩個函數中,當調用fillListBoxData()時,大約一半的時間跳轉到fillDataGridView函數。在第15行,dataAda1.Fill(datTab3);程序立即跳轉到fillDataGridView(string fullName)。我不知道爲什麼。我的代碼跳到一個函數,當它不應該是

有人可以幫助我,並讓這個程序停止這樣做。

public void fillListBoxData() 
    { 
     //Open connection 
     //found in app.config 
     using (SqlConnection conn = new SqlConnection(Properties.Settings.Default.Database1ConnectionString))//database ONE 
     { 
      //open the connection 
      conn.Open(); 

      // Create new DataAdapter 
      using (SqlDataAdapter dataAda1 = new SqlDataAdapter("SELECT (firstName + ' ' + lastName) AS NAME FROM dbo.VolunteerContactInfo", conn)) 
      { 
       // Use DataAdapter to fill DataTable 
       DataTable datTab3 = new DataTable(); 
       dataAda1.Fill(datTab3);     

       //assign the dataTable as the dataSource for the listbox 
       volList.DataSource = datTab3; 
       //display member needed to show text 
       volList.DisplayMember = "NAME"; 
       conn.Close(); 

      } 
     } 
    } 

void fillDataGridView(string fullName) 
    { 
     string tableName = "dbo." + fullName; 
     // Open connection 
     using (SqlConnection conn = new SqlConnection(Properties.Settings.Default.Database2ConnectionString))//database TWO 
     { 
      //open the connection 
      conn.Open(); 

      // Create new DataAdapter 
      using (SqlDataAdapter dataAda = new SqlDataAdapter("SELECT * FROM " + @tableName, conn)) 
      { 
       // Use DataAdapter to fill DataTable 
       DataTable datTab = new DataTable(); 
       dataAda.Fill(datTab); 

       volWorkDataGrid.DataSource = datTab; 

      } 
      conn.Close(); 
     } 
    } 
+0

你怎麼知道它跳到'fillDataGridView'? – Kevin

+0

您的方法'fillDataGridView'可能被註冊爲您的網格的事件處理程序,並且在填充過程中被網格調用。您需要刪除該事件處理程序以防止它被調用。 –

+0

也可能在調試時調試程序在線程間跳轉。 –

回答

2

在「初始化」數據時使用臨時標誌來禁止事件處理程序。

bool _suppressEvent = false; 

public void fillListBoxData() 
{ 
    try 
    { 
     _suppressEvent = true; 

     ...Do whatever you want here 
    } 
    finally 
    { 
     _suppressEvent = false; 
    } 
} 

void volList_SelectedIndexChanged(object sender, EventArgs e) 
{ 
    if(_suppressEvent) return; 

    ... 
} 

在try /終於保證了無論在try子句中發生了什麼(異常,退貨等),您的抑制標誌總是會得到關閉。否則,你可能會遇到一些難以追查的奇怪行爲。

+0

我的程序仍然沒有按預期工作,但這會讓我朝着正確的方向前進。謝謝! – LeonhartDan

相關問題