【问题标题】:Query Database, save results as an object and then fill a DataGridView with the properties of the object查询数据库,将结果保存为对象,然后用对象的属性填充 DataGridView
【发布时间】:2020-08-04 17:53:30
【问题描述】:

在 C# 上试水。我有一个 Winform 程序,用户通过表单注册员工。用户的数据存储在 SQL Server 数据库的表中。 在程序的另一部分,用户应该能够显示所有注册员工及其信息。但是,我不能使用 DataSet 或 DataTable。所以我正在考虑做这样的事情(概念上)

查询数据库 > 创建适当类的新实例 > 将所述对象存储在列表中 > 通过遍历列表填充 DataGridView。

但是,我不知道如何将查询结果“翻译”为类的各个实例。查询不会总是只返回 1 行,而是返回其中的几行,那么如何做到这一点,以便每一行都经历被添加为我存储在中的每个新实例的属性值的过程列表?

假设示例类类似于“Employee”,具有“ID”、“Name”和“Position”属性

【问题讨论】:

    标签: c# database winforms datagridview


    【解决方案1】:

    您只需将属性设置为 DB 值。

    List<Employee> myEmployees = new List<Employee>();
    foreach(DataRow dr in myDatatable.Rows)
    {
      new myEmployee = new Employee {ID = dr["ID"], Name = dr["Name"], Postion = dr["Postion"]};
      myEmployees.Add(myEmployee);
    }
    

    【讨论】:

    • myDataTabla 的类型是什么?我认为这意味着一个 DataTable 对象,但我得到一个“foreach 循环不能对 DataTable 类型的变量进行操作”
    • @Elmambo2194 - 抱歉应该是 myDataTable.Rows
    【解决方案2】:

    假设您的数据库返回 ID、名称和位置作为变量,您可以使用 ObservableCollection 来填充,例如一个数据网格。 最初创建一个存储 Employee 数据的类。

    public class Employee
    {
      public int ID{get; set;}
      public string name{get; set;}
      public string position{get; set;}
    }
    

    接下来在你的 MainWindow 中定义一个依赖属性(Employees)。

    public ObservableCollection<Employee> Employees
    {
      get{return (ObservableCollection<Employee>) GetValue(EmpProperty);}
      set{SetValue(EmpProperty, value);}
    }
    public static readonly DependencyProperty EmpProperty = DependencyProperty.Register
    (
      "Employees", typeof(ObservableCollection<Employee>),
      typeof(MainWindow),
      new PropertyMetadata(null)
    );
    

    在您的 MainWindow 的另一个地方,您会得到查询结果;为简单起见,我假设三个数组 ID_Array、name_Array 和 position_Array 在我的示例中存储计数元素

    ...
    Employees = new ObservableCollection<Employee>
    {
      for(int i = 0, i < count; i++)
      {
        new Employee
        {
          ID = ID_Array[i],
          name = name_Array[i],
          position = position_Array[i];
        };
      }
    }
    ...
    PART_DataGrid.ItemsSource = Employees;
    

    最后在你的 xaml 文件中声明你的 DataGrid

    ...
    <DataGrid x:Name="PART_DataGrid", AutogenerateColumns="false">
      DataGrid.Columns>
      <!-- Define headers as needed -->
        <DataGridTextColumn Header="Employee ID" Binding="{Binding ID}" />
        <DataGridTextColumn Header="Name" Binding="{Binding name}" />
        <DataGridTextColumn Header="Position" Binding="{Binding position}" />
      </DataGrid.Columns>
    </DataGrid>
    

    我还没有测试过代码,但我希望它能给你一个关于如何继续的基本想法。基本上它也应该适用于 WinForms。

    问候马丁

    【讨论】:

    • 这是 WinForms,而不是 WPF。您发布的内容无法正常工作(Employee 类定义除外)。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-11-25
    • 1970-01-01
    • 1970-01-01
    • 2013-04-21
    • 1970-01-01
    • 2016-03-12
    相关资源
    最近更新 更多