在datagridview控件中创建循环语句时,不显示数据

时间:2011-03-01 11:03:54

标签: c# windows datagridview

我有datagridview控件,可以从数据库中检索数据。我有我的代码,但在gridview中没有数据。我在循环中做了一个断点,但在DataGridViewTextBoxCell Number = (DataGridViewTextBoxCell)DGCategory.Rows[i].Cells[l];时  数据网格视图apeared没有数据

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();

                    }

                }
            }
        }
    }

1 个答案:

答案 0 :(得分:1)

如果您想从数据库中获取值到网格视图中,请使用以下内容:
例如,在名为“selectCommand”的String中编写查询,然后使用数据集获取结果:

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 是您希望结果显示在的数据网格视图的名称。
 请注意,您应该提供与数据库的连接以便接收结果。