如何遍历数据库表以在datagrid中添加数据?

时间:2017-08-15 15:28:24

标签: c# mysql wpf datagrid logic

我有从数据库表读取到datagrid的代码,但它只运行一次,并从数据库中将顶行添加到datagrid。有没有办法可以多次运行它来读取不同行的数据并将其添加到我的数据网格中。

 public static void AddData( DataGrid datagrid)
 {
        SqlConnection connect = GetConnection();
        SqlCommand command = new SqlCommand();
        command.Connection = connect;

        //connect to database
        connect.Open();
        command.CommandText = "Select req_status From TH_request where req_status = 'N'";
        command.ExecuteNonQuery();
        status = (String)command.ExecuteScalar();
        connect.Close();

        connect.Open();
        command.CommandText = "Select req_date_time From TH_request where req_status = 'N'";
        command.ExecuteNonQuery();
        time = (DateTime)command.ExecuteScalar();
        connect.Close();

        connect.Open();
        command.CommandText = "Select resp_user_name From TH_request where req_status = 'N'";
        command.ExecuteNonQuery();
        locationName = (String)command.ExecuteScalar();
        connect.Close();

        collection.Add(new DataObject()
        {
             A = time,
             B = locationName,
             C = status,
             D = respUserName
        });
        datagrid.ItemsSource = collection;

}

1 个答案:

答案 0 :(得分:0)

您只需执行一次命令即可。然后,您可以使用SqlDataReader为查询返回的每一行创建DataObject

public static void AddData(DataGrid datagrid)
{
    collection.Clear();
    using (SqlConnection connection = GetConnection())
    {
        using (SqlCommand command = new SqlCommand("Select req_status, req_date_time, resp_user_name From TH_request where req_status = 'N'", connection))
        {
            connection.Open();
            using (SqlDataReader reader = command.ExecuteReader())
            {
                while (reader.Read())
                {
                    collection.Add(new DataObject()
                    {
                        A = Convert.ToDateTime(reader["req_date_time"]),
                        B = Convert.ToString(reader["resp_user_name"]),
                        C = Convert.ToString(reader["req_status"]),
                        D = respUserName
                    });
                }

            }
        }
    }
    datagrid.ItemsSource = collection;
}