2010-12-02 106 views
0

的實例我有這樣對象引用不設置到對象

public void GetTablesWithUpperCaseName() 
{ 
    SqlConnectionStringBuilder objConnectionString = new SqlConnectionStringBuilder(); 
    objConnectionString.DataSource = txtHost.Text; 
    objConnectionString.UserID = txtUsername.Text; 
    objConnectionString.Password = txtPassword.Text; 
    objConnectionString.InitialCatalog = Convert.ToString(cmbDatabases.SelectedValue); 

    SqlConnection sConnection = new SqlConnection(objConnectionString.ConnectionString); 

    //To Open the connection. 
    sConnection.Open(); 

    //Query to select table_names that have their names in uppercase letters. 
    string selectTablesWithUppercaseName = @"SELECT 
               NAME 
              FROM 
               sysobjects 
              WHERE 
               UPPER(name) COLLATE Latin1_General_BIN = name COLLATE Latin1_General_BIN 
               AND 
               OBJECTPROPERTY(ID,N'IsTable')=1 
               AND 
               OBJECTPROPERTY(ID,N'IsMSShipped')=0 "; 
    //Create the command object 
    SqlCommand sCommand = new SqlCommand(selectTablesWithUppercaseName, sConnection); 

    try 
    { 
     //Create the dataset 
     DataSet dsListOfTablesWithUppercaseName = new DataSet("sysobjects"); 

     //Create the dataadapter object 
     SqlDataAdapter sDataAdapter = new SqlDataAdapter(selectTablesWithUppercaseName, sConnection); 

     //Provides the master mapping between the sourcr table and system.data.datatable 
     sDataAdapter.TableMappings.Add("Table", "sysobjects"); 

     //Fill the dataset 
     sDataAdapter.Fill(dsListOfTablesWithUppercaseName); 

     //Bind the result combobox with foreign key table names 
     DataViewManager dvmListOfForeignKeys = dsListOfTablesWithUppercaseName.DefaultViewManager; 
     dgResultView.DataSource = dsListOfTablesWithUppercaseName.Tables["sysobjects"]; 
    } 
    catch(Exception ex) 
    { 
     //All the exceptions are handled and written in the EventLog. 
     EventLog log = new EventLog("Application"); 
     log.Source = "MFDBAnalyser"; 
     log.WriteEntry(ex.Message); 
    } 
    finally 
    { 
     //If connection is not closed then close the connection 
     if(sConnection.State != ConnectionState.Closed) 
     { 
      sConnection.Close(); 
     } 
    } 
} 

一個功能和用於計數從前面的函數生成的行另一功能。但是,這個功能

空引用異常或對象 未設置爲 對象的實例..

誰能幫我在這......爲什麼只對功能捕獲錯誤以上並且對所有其他類似功能都可以正常工作

private void UpdateLabelText() 
{ 
    SqlConnectionStringBuilder objConnectionString = new SqlConnectionStringBuilder(); 
    objConnectionString.DataSource = txtHost.Text; 
    objConnectionString.UserID = txtUsername.Text; 
    objConnectionString.Password = txtPassword.Text; 
    objConnectionString.InitialCatalog = Convert.ToString(cmbDatabases.SelectedValue); 

    SqlConnection sConnection = new SqlConnection(objConnectionString.ConnectionString); 

    //To Open the connection. 
    sConnection.Open(); 

    try 
    { 
     int SelectedCellTotal = 0; 
     int counter; 

     // Iterate through the SelectedCells collection and sum up the values. 
     for(counter = 0;counter < (dgResultView.SelectedCells.Count);counter++) 
     { 
      if(dgResultView.SelectedCells[counter].FormattedValueType == Type.GetType("System.String")) 
      { 
       string value = null; 

       // If the cell contains a value that has not been commited, 
       if(dgResultView.IsCurrentCellDirty == true) 
       { 
        value = dgResultView.SelectedCells[counter].EditedFormattedValue.ToString(); 
       } 
       else 
       { 
        value = dgResultView.SelectedCells[counter].FormattedValue.ToString(); 
       } 
       if(value != null) 
       { 
        // Ignore cells in the Description column. 
        if(dgResultView.SelectedCells[counter].ColumnIndex != dgResultView.Columns["TABLE_NAME"].Index) 
        { 
         if(value.Length != 0) 
         { 
          SelectedCellTotal += int.Parse(value); 
         } 
        } 
       } 
       } 
      } 

      // Set the labels to reflect the current state of the DataGridView. 
      lblDisplay.Text = "There are Total " + dgResultView.RowCount + cmbOperations.SelectedItem.ToString(); 
     } 
     catch(Exception ex) 
     { 
      //All the exceptions are handled and written in the EventLog. 
      EventLog log = new EventLog("Application"); 
      log.Source = "MFDBAnalyser"; 
      log.WriteEntry(ex.Message); 
     } 
     finally 
     { 
      //If connection is not closed then close the connection 
      if(sConnection.State != ConnectionState.Closed) 
      { 
       sConnection.Close(); 
      } 
     } 
    } 

此外,lblDisplay.Text未採取適當的空格。

等待回覆

+6

你提供了很多代碼......哪一行是拋出異常? – 2010-12-02 13:09:58

回答

4

OK,我真的沒有,爲什麼你得到一個「空引用異常」的答案 - 但有幾個點在扔,但是:

  • 我會用sys.tables代替sysobjects且指定要查詢什麼類型的對象爲

  • ALWAYS把你一次性SqlConnectionSqlCommand轉換爲using(.....) { ...... }塊。這樣的話,你將不再需要任何finally {..}塊,當他們不再需要

  • 爲什麼要使用一個DataSet .NET將採取妥善處理這些對象的照顧時,你只裏面有一個表??這只是不必要的開銷 - 改用DataTable

  • 不要打開SqlConnection,早期 - 等待,直到最後一刻,打開它,執行查詢,再次關閉它馬上

  • 實際上,使用SqlDataAdapter時,你不需要給自己開SqlConnection在所有 - 的SqlDataAdapter會爲你做(和再次關閉它完成讀取數據後)

  • 從數據庫綁定到混合數據的檢索UI元素 - 這是一個非常糟糕的做法。從GetTablesWithUpperCaseName方法,你應該返回的東西(如DataTable)給調用者(用戶界面),並讓UI處理綁定過程

  • 沿着相同的路線

    :這種方法應該從UI抓住的東西元素(如文本框)本身 - 通過在這些值作爲方法的參數,以獲得更乾淨的代碼 - 一個你威力居然能在另一個項目中的某一天重用

這是我怎麼想的你的第一種方法應該看起來像

public DataTable GetTablesWithUpperCaseName(string server, string database, 
               string username, string password) 
    { 
     // Create the datatable 
     DataTable dtListOfTablesWithUppercaseName = new DataTable("tableNames"); 

     SqlConnectionStringBuilder objConnectionString = new SqlConnectionStringBuilder(); 
     objConnectionString.DataSource = server;; 
     objConnectionString.UserID = username; 
     objConnectionString.Password = password; 
     objConnectionString.InitialCatalog = database; 

     // Define the Query against sys.tables - much easier and cleaner! 
     string selectTablesWithUppercaseName = 
      "SELECT NAME FROM sys.tables WHERE UPPER(name) COLLATE Latin1_General_BIN = name COLLATE Latin1_General_BIN AND is_msshipped = 0"; 

     // put your SqlConnection and SqlCommand into using blocks! 
     using (SqlConnection sConnection = new SqlConnection(objConnectionString.ConnectionString)) 
     using (SqlCommand sCommand = new SqlCommand(selectTablesWithUppercaseName, sConnection)) 
     { 
      try 
      { 
       // Create the dataadapter object 
       SqlDataAdapter sDataAdapter = new SqlDataAdapter(selectTablesWithUppercaseName, sConnection); 

       // Fill the datatable - no need to open the connection, the SqlDataAdapter will do that all by itself 
       // (and also close it again after it is done) 
       sDataAdapter.Fill(dtListOfTablesWithUppercaseName); 
      } 
      catch (Exception ex) 
      { 
       //All the exceptions are handled and written in the EventLog. 
       EventLog log = new EventLog("Application"); 
       log.Source = "MFDBAnalyser"; 
       log.WriteEntry(ex.Message); 
      } 
     } 

     // return the data table to the caller 
     return dtListOfTablesWithUppercaseName; 
    } 
相關問題