Introduction

In this article, we will learn how to convert a DataSet and DataReader to a list using a simple WPF application.

(This is simple only but many people are unaware of it so that is why I posted this article.)

Procedure

Step 1

Create a new project using "File" > "New" > "Project..." > "WPF Application" and name it: "ListConversions".


Step 2
Now to design your MainWindow.xaml View design part use the following code:

  1. <Window x:Class="DataReaderToList.MainWindow"
  2. xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
  3. xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
  4. Title="EmployeeList" Height="350" Width="525">
  5. <Grid>
  6. <Grid.RowDefinitions>
  7. <RowDefinition Height="*"/>
  8. </Grid.RowDefinitions>
  9. <DataGrid AutoGenerateColumns="False" ItemsSource="{Binding Path=EmployeeList}">
  10. <DataGrid.Columns>
  11. <DataGridTextColumn Header="Empno" Binding="{Binding Path=Eno}" Width="100"/>
  12. <DataGridTextColumn Header="Empname" Binding="{Binding Path=Ename}" Width="130"/>
  13. <DataGridTextColumn Header="Job" Binding="{Binding Path=Job}" Width="130"/>
  14. <DataGridTextColumn Header="Salary" Binding="{Binding Path=Salary}" Width="150"/>
  15. </DataGrid.Columns>
  16. </DataGrid>
  17. </Grid>
  18. </Window>
Step 3
You will get the MainWindow.xaml window as below.

Step 4
Now add the configuration settings to the App.config file as iin the following (the username and word may be different in your SQL Server).
  1. <?xml version="1.0" encoding="utf-8" ?>
  2. <configuration>
  3. <startup>
  4. <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5" />
  5. </startup>
  6. <connectionStrings>
  7. <add name="ConString" connectionString="Data Source=.; User Id=sa;word=Test123!;Database=WpfPractice" providerName="System.Data.SqlClient"/>
  8. </connectionStrings>
  9. </configuration>
Step 5
The following is the code for converting the DataReader to a List.
  1. using System;
  2. using System.Collections.ObjectModel;
  3. using System.Configuration;
  4. using System.Data;
  5. using System.Data.SqlClient;
  6. using System.Windows;
  7. namespace DataReaderToList.ViewModels
  8. {
  9. class DataReaderToListModel
  10. {
  11. #region Varible declarations
  12. private SqlConnection _sqlConnection;
  13. private SqlCommand _sqlCommand;
  14. private SqlDataReader _sqlDataReader;
  15. private string _strsqlcommand;
  16. #endregion
  17. #region Constructor
  18. public DataReaderToListModel()
  19. {
  20. EmployeeList = new ObservableCollection<EmployeeModel>();
  21. LoadData();
  22. }
  23. #endregion
  24. public ObservableCollection<EmployeeModel> EmployeeList { get; set; }
  25. #region Method for Getting the data from Databse
  26. public void LoadData()
  27. {
  28. try
  29. {
  30. _sqlConnection = new SqlConnection(ConfigurationManager.ConnectionStrings["ConString"].ConnectionString);
  31. if (_sqlConnection.State != ConnectionState.Open)
  32. _sqlConnection.Open();
  33. _strsqlcommand = "Select *From Emp";
  34. _sqlCommand = new SqlCommand(_strsqlcommand, _sqlConnection);
  35. _sqlDataReader = _sqlCommand.ExecuteReader();
  36. var employeemodellist = new ObservableCollection<EmployeeModel>();
  37. while (_sqlDataReader.Read())
  38. {
  39. var employeeModel = new EmployeeModel
  40. {
  41. Eno = _sqlDataReader.GetInt32(_sqlDataReader.GetOrdinal("Empno")),
  42. Ename = _sqlDataReader.GetString(_sqlDataReader.GetOrdinal("Ename")),
  43. Job = _sqlDataReader.GetString(_sqlDataReader.GetOrdinal("Job")),
  44. Salary = _sqlDataReader.GetDecimal(_sqlDataReader.GetOrdinal("Sal"))
  45. };
  46. employeemodellist.Add(employeeModel);
  47. }
  48. EmployeeList = employeemodellist;
  49. _sqlConnection.Close();
  50. }
  51. catch (Exception exception)
  52. {
  53. MessageBox.Show("DataLoading Failed beacause of following Reason \n" + exception.Message, "Error", MessageBoxButton.OK, MessageBoxImage.Error);
  54. }
  55. }
  56. #endregion
  57. }
  58. class EmployeeModel
  59. {
  60. #region Properties
  61. public int Eno { get; set; }
  62. public string Ename { get; set; }
  63. public string Job { get; set; }
  64. public decimal Salary { get; set; }
  65. #endregion
  66. }
  67. }
Step 6
The following is the code for converting the DataSet to a List.
  1. using System.Windows;
  2. using System;
  3. using System.Collections.ObjectModel;
  4. using System.Data;
  5. using System.Data.SqlClient;
  6. using System.Configuration;
  7. namespace WpfApplication1.ViewModels
  8. {
  9. class MainWindowViewModelcs
  10. {
  11. #region Variable Declaration
  12. private SqlConnection _cn;
  13. private SqlDataAdapter _da;
  14. private DataSet _ds;
  15. private string _strsqlcommand;
  16. #endregion
  17. #region Constructor
  18. public MainWindowViewModelcs()
  19. {
  20. EmployeeList = new ObservableCollection<EmployeeModel>();
  21. LoadData();
  22. }
  23. #endregion
  24. public ObservableCollection<EmployeeModel> EmployeeList { get; set; }
  25. #region Method for getting the data from database
  26. public void LoadData()
  27. {
  28. try
  29. {
  30. _cn = new SqlConnection(ConfigurationManager.ConnectionStrings["ConString"].ConnectionString);
  31. if (_cn.State != ConnectionState.Open)
  32. _cn.Open();
  33. _strsqlcommand = "Select *From Emp";
  34. _da = new SqlDataAdapter(_strsqlcommand, _cn);
  35. _ds = new DataSet();
  36. _da.Fill(_ds, "Employee");
  37. var dt = _ds.Tables["Employee"];
  38. var employeemodellist = new ObservableCollection<EmployeeModel>();
  39. for (int i = 0; i < dt.Rows.Count; i++)
  40. {
  41. var om = new EmployeeModel
  42. {
  43. Eno = Convert.ToInt32(dt.Rows[i]["Empno"]),
  44. Ename = dt.Rows[i]["Ename"].ToString(),
  45. Job = dt.Rows[i]["Job"].ToString(),
  46. Salary = Convert.ToDecimal(dt.Rows[i]["Sal"].ToString()),
  47. };
  48. employeemodellist.Add(om);
  49. }
  50. EmployeeList = employeemodellist;
  51. _cn.Close();
  52. }
  53. catch (Exception exception)
  54. {
  55. MessageBox.Show("DataLoading Failed beacause of following Reason \n" + exception.Message, "Error", MessageBoxButton.OK, MessageBoxImage.Error);
  56. }
  57. }
  58. #endregion
  59. }
  60. class EmployeeModel
  61. {
  62. #region Properties
  63. public int Eno { get; set; }
  64. public string Ename { get; set; }
  65. public string Job { get; set; }
  66. public decimal Salary { get; set; }
  67. #endregion
  68. }
  69. }
Step 7
The following is the output window you will get after executing the project.
I hope you find this article useful. Please provide your valuable feedback, question, or comments about this article.