在 Win Forms 应用程序中,UI 中有一个网格 View ,其中应填充客户端分支机构的详细信息。大约有50家分店。因此,GetBranchDetails() 类中的 DataService 方法返回一个 DataSetPresenter 类将该 DataSet 传递给 UI 的 BindData() 方法,在该方法中,网格 View 的 datasource 属性设置为 DataSet 对象,如代码所示。

问题是 DataService 没有返回模型,而是返回 DataSet 。有人可以告诉我如何在这里使用 BranchOffice 模型而不是使用 DataSet 吗?这样 Model 应该从 DataService 返回,然后 presenter 将该 Model 传递给 UI,在 UI 中 Model 将被设置为网格 View 的 datasource。请注意,分公司总是不止一个!

数据服务类

        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;
           }
        }

演示者类
private void _View_ShowBranches(object sender, EventArgs e)
{
    ShowBranches();
}

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

View /用户界面
public partial class frmAttendancePoints : Form, IView
{
    public frmAttendancePoints()
    {
        InitializeComponents();
    }

    public void BindData(DataSet dt)
    {
        dgAttendancePoints.DataSource = dt;
    }
}

最佳答案

使用此方法将 ADO.NET DataTable 转换为可以在 MVP View 中显示的 JSON:

 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);
    }

关于c# - 如何使用 MVP 中的模型填充数据网格 View ,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/23510205/

10-14 19:26
查看更多