c# - 试图将表格记录一张一张地获取到datagridview

标签 c# mysql sql-server

这是我的代码,但这仅提供最后一条记录。但我需要一条一条的记录

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/

相关文章:

c# - 无法创建 MemoryStream

mysql - 我的数据库中的 "Weird"值

sql-server - 从 Docker 内部使用 sqlcmd 连接到 SQL Server 时出现问题

sql-server - 如何针对链接服务器执行存储过程?

sql - 如何解决 Msg 8115, Level 16, State 2, Line 2 算术溢出错误将表达式转换为数据类型 int.?

c# - 重构代码以避免类型转换

c# - 您将如何实现 IEnumerator 接口(interface)?

c# - XNA - GraphicsDevice 初始化困惑

javascript - 从 href 链接打开一个弹出窗口并将数据传递给子项

mysql - 查询返回的访问计数