2011-03-01 37 views
0

我有datagridview控件,它從數據庫中檢索數據。我有我的代碼做到這一點,但沒有數據在gridview中顯示。我做的環一個破發點,但是當DataGridViewTextBoxCell Number = (DataGridViewTextBoxCell)DGCategory.Rows[i].Cells[l]; 數據網格視圖沒有數據apeared在datagridview控件中創建循環語句時不顯示數據

private void getcategory() 
     { 
      for (int i = 0; i < DGCategory.Rows.Count; i++) 
      { 
       for (int l = 0; l < DGCategory.Rows[i].Cells.Count; l++) 
       { 
        DataGridViewTextBoxCell Number = (DataGridViewTextBoxCell)DGCategory.Rows[i].Cells[l]; 
        DataGridViewTextBoxCell Category = (DataGridViewTextBoxCell)DGCategory.Rows[i].Cells[l]; 
        DataGridViewTextBoxCell Parent = (DataGridViewTextBoxCell)DGCategory.Rows[i].Cells[l]; 
        DataGridViewCheckBoxCell Active = (DataGridViewCheckBoxCell)DGCategory.Rows[i].Cells[l]; 
        DataGridViewTextBoxCell AddDate = (DataGridViewTextBoxCell)DGCategory.Rows[i].Cells[l]; 

       using (SqlConnection Con = GetConnection()) 
       { 
        SqlCommand cmd = new SqlCommand("SP_GetAllCategories", Con); 
        cmd.CommandType = CommandType.StoredProcedure; 
        SqlDataReader dr; 
        dr = cmd.ExecuteReader(); 
        if (dr.Read()) 
        { 
         Number.Value = dr["Number"].ToString(); 
         Category.Value = dr["Category"].ToString(); 
         Parent.Value = dr["Parent"].ToString(); 
         Active.Value = dr["Active"].ToString(); 
         AddDate.Value = dr["AddDate"].ToString(); 

        } 

       } 
      } 
     } 
    } 
+0

我不知道你正在試圖用這些循環做什麼。 – 2011-03-01 11:33:02

回答

1

如果妳想從你的數據庫值到網格視圖..使用以下命令:
編寫查詢在一個叫「的SelectCommand」例如字符串,然後使用數據集得到的結果:

public DataSet GetSearchEmpResults(string emp_fn) 
{ 
string selectCommand = @"select 
           emp.first_name as 'First Name', 
           emp.last_name as 'Last Name' 
           from Employees emp 
           where emp.first_name = '" + emp_fn + "';"; 
SqlCommand command = new SqlCommand(selectCommand, this.Connection); 
DataSet ds = new DataSet("Results"); 
SqlDataAdapter da = new SqlDataAdapter(command); 
da.Fill(ds, "Results"); 
return ds; 
} 
數據GridView控件代碼

則:

DataSet results = db.GetSearchEmpResults(fristName, lastName); //this depends on your results 
dataGridViewResults.DataSource = results; 
dataGridViewResults.DataMember = "Results"; 

dataGridViewResults是您希望的結果喲出現。
請注意,您應該提供以接收結果數據庫的連接的數據GridView控件的名稱。