2011-03-01 63 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控件的名称。