Data does not display when making loop statement in datagridview control
I had datagridview control which retrieves data from database. I had my code to do that, but no data apeared in gridview. I made a break point in the loop but when on DataGridViewTextBoxCell Number = (DataGridViewTextBoxCell)DGCategory.Rows[i].Cells[l];
datagrid view apeared with no data
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];
DataGridViewCheckBoxCel开发者_高级运维l 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();
}
}
}
}
}
If u want to get values from your database into a grid view .. use the following:
write your query in a String called "selectCommand" for example then use a dataset to get the results:
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;
}
then in the data gridview code:
DataSet results = db.GetSearchEmpResults(fristName, lastName); //this depends on your results
dataGridViewResults.DataSource = results;
dataGridViewResults.DataMember = "Results";
the dataGridViewResults is the name of the data gridview you want your results yo appear in.
Note that you should provide the connection to your database in order to receive the results.
精彩评论