How to populate a data grid view using a model in MVP

In the application of the win form, a grid is displayed in the user interface, which must be filled with the details of the client branches. There are about 50 branches. Thus, the method GetBranchDetails()in the class DataServicereturns the class DataSet, and the class Presenterpasses DataSetto the UI method BindData(), in which the datasourcegrid view property is set to DataSet, as shown in the code.

The problem is that it DataServicedoes not return the model, but returns << 22>. Can someone tell me how to use the model BranchOfficeinstead of using DataSethere? That Modelshould have been returned from DataService, and then it Presenterwill transfer this Modelto the UI, where it Modelwill be installed as datasourcea grid. Please note that there will always be more than one branch!

Class DataService

        public DataTable GetBranchDetails()
        {
            string selectStatement = "SELECT ID, branch_name + ', ' + branch_add AS Branch,       area, sm, atten_status FROM Branch WHERE Status='Active'";
            using (SqlConnection sqlConnection = new   SqlConnection(db.GetConnectionString))
            using (SqlCommand sqlCommand = new SqlCommand(selectStatement, sqlConnection))
            using (SqlDataAdapter da = new SqlDataAdapter(sqlCommand))
            using (DataSet ds = new DataSet())
            using (DataTable dt = new DataTable())
           {
              ds.Tables.Add(dt);    
              sqlConnection.Open();
              da.Fill(dt);
              return dt;
           }
        }

Presenter class

private void _View_ShowBranches(object sender, EventArgs e)
{
    ShowBranches();
}

private void ShowBranches()
{
    var dt = DataService.GetBranchDetails();
    this._View.BindData(dt);
}

Browse / UI

public partial class frmAttendancePoints : Form, IView
{
    public frmAttendancePoints()
    {
        InitializeComponents();
    }

    public void BindData(DataSet dt)
    {
        dgAttendancePoints.DataSource = dt;
    }
}
+4
source share
1 answer

Use this method to convert an ADO.NET DataTable to JSON, which can be represented in an MVP view:

 string GetJson(DataTable table)
    {
        System.Web.Script.Serialization.JavaScriptSerializer serializer = new System.Web.Script.Serialization.JavaScriptSerializer();
        List<Dictionary<string, object>> rows = new List<Dictionary<string, object>>();
        Dictionary<string, object> row = null;
        foreach (DataRow dataRow in table.Rows)
        {
            row = new Dictionary<string, object>();
            foreach (DataColumn column in table.Columns)
            {
                row.Add(column.ColumnName.Trim(), dataRow[column]);
            }
            rows.Add(row);
        }
        return serializer.Serialize(rows);
    }
+1
source

Source: https://habr.com/ru/post/1539521/


All Articles