2010-12-02 102 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; 
    } 
相关问题