这是我的代码,但这仅提供最后一条记录。但我需要一条一条的记录
string query = "select * from tbl_users;";
SqlCommand com = new SqlCommand(query, con);
con.Open();
SqlDataReader reader = com.ExecuteReader();
for (int x = 0; x <= total; x++)
{
dataGridView1.Rows.Add();
while (reader.Read())
{
dataGridView1.Rows[x].Cells["colNic"].Value = reader["NIC"].ToString();
dataGridView1.Rows[x].Cells["colName"].Value = reader["name"].ToString();
dataGridView1.Rows[x].Cells["colAge"].Value = reader["age"].ToString();
dataGridView1.Rows[x].Cells["colCity"].Value = reader["city"].ToString();
}
}
con.Close();
最佳答案
我从上面理解的是,你实际上想在 datagridview 中添加每条记录作为行,所以下面应该是代码:
string query = "select * from tbl_users;";
SqlCommand com = new SqlCommand(query, con);
con.Open();
SqlDataReader reader = com.ExecuteReader();
while (reader.Read())
{
int x = dataGridView1.Rows.Add(); // add new row for each db row in grid
// and use index returned by it
DataGridViewRow currentRow = dataGridView1.Rows[x];
currentRow.Cells["colNic"].Value = reader["NIC"].ToString();
currentRow.Cells["colName"].Value = reader["name"].ToString();
currentRow.Cells["colAge"].Value = reader["age"].ToString();
currentRow .Cells["colCity"].Value = reader["city"].ToString();
}
dataGridView1.Rows.Add()
将为新创建的行返回索引,因此您应该使用它,实际上您不需要那个 for
循环,只需使用 while
迭代所有返回的行,并在网格中逐一添加行。
这里的另一个建议是,如果您只需要特定的列,那么在从表中选择记录时不要使用 *
,始终在查询中指定您需要的列,例如:
SELECT NIC,name,age,city FROM tbl_users
希望对您有所帮助。
关于c# - 试图将表格记录一张一张地获取到datagridview,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48814223/