2012-04-22 32 views
0

我想問更多使用數據網格將數據從SQL Server顯示到WinForm。 我一直在創造一個DataGrid和存儲過程來顯示數據是如何使用C#+數據網格顯示數據SQL Server

ALTER PROC [dbo].[SP_GetData] 
AS 
    SELECT nama , nim 
    FROM tabledata 

和我創建訪問數據庫和存儲過程在C#中的功能

string Sp_Name = "dbo.SP_GetData"; 

SqlConnection SqlCon = new SqlConnection("Integrated Security=SSPI;Persist Security Info=False;Initial Catalog=DBMahasiswa;Data Source=."); 
SqlCon.Open(); 

SqlCommand SqlCom = new SqlCommand(Sp_Name , SqlCon); 
SqlCom.CommandType = CommandType.StoredProcedure; 

List<mahasiswaData> listMahasiswa = new List<mahasiswaData>(); 

using (SqlDataReader sqlDataReader = SqlCom.ExecuteReader()) 
{ 
    if (sqlDataReader.HasRows) 
    { 
     while (sqlDataReader.Read()) 
     { 
     mahasiswaData DataMhs = new mahasiswaData(); 
     DataMhs.Nama = sqlDataReader["Name"].ToString(); 
     DataMhs.Umur = Convert.ToInt32(sqlDataReader["Age"]); 
     listMahasiswa.Add(DataMhs); 
     } 
    } 
} 

SqlCon.Close(); 
return listMahasiswa; 

最後,在顯示按鈕,我添加此代碼

dgvmahasiswa.DataSource = new MahasiswaDB().LoadMahasiswa(); 

有人可以告訴我哪裏是故障或替代品嗎?

非常感謝你! :d

+0

究竟是什麼問題呢?除了建議進行一些重構,不要在catch塊中返回null(你至少應該記錄錯誤,以便知道事情是否出錯),以及更多地使用using關鍵字,這看起來好像會起作用。另外請注意,如果您的查詢運行但沒有返回任何行,您只需返回一個空列表mahasiswa – dash 2012-04-22 14:49:03

+0

非常感謝評論:) :) 我已經添加了try - catch以防止出現一些錯誤.. 但是,我仍然總是收到虛假的回報.. 僅供參考,我已經添加了一些數據到數據庫中的表.. – pegasustech 2012-04-23 04:20:22

回答

2

有些事情要考慮:

  1. 此刻,如果你的代碼運行到異常,你會離開一個 的SqlConnection遊逛;你已經使用了你的 SqlDataReader的使用模式;你應該把它擴展到你所有的一次性的對象 。

  2. 您正在吞嚥異常;如果您的查詢失敗,則無法建立連接 ,或發生其他事情,您永遠不會知道 - 您的函數將僅返回null。

  3. 名稱或年齡可能爲空嗎?年齡是非數字? 有沒有測試任何意外的價值觀,你也永遠不會知道 。

  4. 如果您沒有任何記錄,則會返回空白列表。這是 需要嗎?或者你想知道沒有記錄?

你可能喜歡看這樣的事情:

public List<mahasiswaData> GetData(){ 


    List<mahasiswaData> gridData = new List<mahasiswaData>(); 


    try{ 

     using(SqlConnection conn = new SqlConnection("Integrated Security=SSPI;Persist Security Info=False;Initial Catalog=DBMahasiswa;Data Source=.")) 
     { 
      using(SqlCommand command = new SqlCommand()) 
      { 
       command.Connection = conn; 
       command.CommandType = CommandType.StoredProcedure; 
       command.Text = "dbo.SP_GetData"; 

       using(SqlDataReader reader = command.ExecuteReader()) 
       { 
        if(reader.HasRows){ 
         while(reader.Read()) 
         { 
          object rawName = reader.GetValue(reader.GetOrdinal("Name")); 
          object rawAge = reader.GetValue(reader.GetOrdinal("Age")); 

          if(rawName == DBNull.Value || rawAge == DBNull.Value) 
          { 
           //Use logging to indicate name or age is null and continue onto the next record 
           continue; 
          } 
          //Use the object intializer syntax to create a mahasiswaData object inline for simplicity 
          gridData.Add(new mahasiswaData() 
                { 
           Nama = Convert.ToString(rawName), 
                 Umur = Convert.ToInt32(rawAge) 
                }); 


         } 
        } 
        else{ 
         //Use logging or similar to record that there are no rows. You may also want to raise an exception if this is important. 
        } 

       } 

      } 


     } 


    } 
    catch(Exception e) 
    { 
     //Use your favourite logging implementation here to record the error. Many projects use log4Net 
     throw; //Throw the error - display and explain to the end user or caller that something has gone wrong! 
    } 


    return gridData; 


} 

請注意,如果您確定年齡或名字永遠不會爲空,那麼你可以簡化中間部分:

while (reader.Read()) 
{ 
    //Use the object intializer syntax to create a mahasiswaData object inline for simplicity 
    gridData.Add(new mahasiswaData() 
    { 
     Nama = reader.GetString(reader.GetOrdinal("Name")), 
     Umur = reader.GetInt32(reader.GetOrdinal("Age")) 
    }); 

} 
+0

大讚賞:D:D 我想嘗試你的代碼,但讓我學習你的代碼片刻。 。:) 我可以多問一些問題,我不編輯數據網格屬性中的所有內容。只需在它們後面添加一些代碼。 它有什麼問題嗎? – pegasustech 2012-04-23 04:37:12

+0

不應該有@pegasustech。它應該可以工作,但它可能看起來不像所有必要的屬性所能做的那麼好。首先需要獲取數據,然後*演示網格。 – dash 2012-04-23 07:29:06

+0

大謝謝@dash 看來你是最近回答我的問題的人:D:D 現在問題解決了,主要問題是我指向另一個數據庫在我的sql服務器上.. 非常感謝:) – pegasustech 2012-04-24 11:24:54

相關問題