将嵌套的选择值检索到datatable c#中

时间:2017-04-11 06:53:41

标签: c# sql asp.net datatable asmx

我有从SQL数据库填充的数据表。表格的标题是项目名称和团队成员。我想从Projects表和User_Projects表中的Team成员中检索项目名称,并将它们显示在数据表中。所有项目名称都成功显示,但我不知道如何显示每个项目的团队成员。我希望结果如下: enter image description here

这是我的代码:

ASPX:

<script type="text/javascript">  
   $(document).ready(function () {
      $.ajax({
        type: "POST",
        dataType: "json",
        url: "ProjectMembersService.asmx/GetProjects",
        success: function (data) {
        var datatableVariable = $('#projects-progress').DataTable({
           data: data,
           columns: [
                   { 'data': 'project_name' },
                   { 'data': 'developer_name' },
                    ]
            });
         }
      });
  });
</script> 
<table id="projects-progress" class="table table-striped projects">
  <thead>
     <tr>
        <th style="width: 20%">Project Name</th>
        <th>Team Members</th>
     </tr>
  </thead>
</table> 

ProjectMembersService.asmx:

<%@ WebService Language="C#" CodeBehind="~/App_Code/ProjectMembersService.cs" Class="WebSite1.ProjectMembersService" %>

// using statements


namespace WebSite1
{
    public class ProjectMembersService : System.Web.Services.WebService
    {

        [WebMethod]
        public void GetProjects()
        {
            SqlConnection conn = new SqlConnection("Data Source=RC-8573\\SQLEXPRESS;Initial Catalog=DataManagment;Integrated Security=SSPI");

            var projects = new List<Projects>();
            var developers = new List<Developers>();

            using (conn)
            {
                var cmd = new SqlCommand("getProjects", conn) { CommandType = CommandType.StoredProcedure }; //select all projects inProjects table 
                conn.Open();
                var dr = cmd.ExecuteReader();
                while (dr.Read())
                {
                    var Project = new Projects
                    {
                       project_number = Convert.ToInt32(dr[1].ToString()),
                       project_name = dr[2].ToString(),
                    };
                    projects.Add(Project);    // This ok, it fill the datatable with all project_names

            // here I want for each project to retrieve the team members and display them in Team Members column

            SqlCommand com = new SqlCommand("SELECT user_name FROM Users WHERE user_id = (SELECT user_id FROM User_Projects WHERE project_number = @project_number)", conn); // retrieve all developers name 
                    SqlDataAdapter da = new SqlDataAdapter(com);
                    DataSet ds = new DataSet();
                    da.Fill(ds);

                    var Developer = new Developers
                    {
                        developer_name = ds.Tables[0].Columns["user_name"].ToString();
                    };

                    developers.Add(Developer);


                }
           }
        var js = new JavaScriptSerializer();
        Context.Response.Write(js.Serialize(projects));

        var js2 = new JavaScriptSerializer();
        Context.Response.Write(js2.Serialize(developers));
        }
    }
}

1 个答案:

答案 0 :(得分:1)

您需要根据您所做的列定义向developer_name类添加名为Project的字段。

class Projects
{
    public int project_number { get; set; }
    public string project_name { get; set; }
    public string developer_name { get; set; }
}

并添加set developer names

    using (SqlConnection conn = new SqlConnection("Data Source=RC-8573\\SQLEXPRESS;Initial Catalog=DataManagment;Integrated Security=SSPI;MultipleActiveResultSets=True"))
    {
        var projects = new List<Projects>();
        conn.Open();
        using (var cmd = new SqlCommand("getProjects", conn) { CommandType = CommandType.StoredProcedure })
        using (SqlDataReader dr = cmd.ExecuteReader())
        {
            if (dr.HasRows)
                while (dr.Read())
                {
                    var Project = new Projects
                    {
                        project_number = Convert.ToInt32(dr[1].ToString()),
                        project_name = dr[2].ToString(),
                    };
                    projects.Add(Project); 
                    // open new sqldatareader for each project_id >>  need add MultipleActiveResultSets=True to connectionstring(added)
                    using (SqlCommand com = new SqlCommand("SELECT user_name FROM Users WHERE user_id IN (SELECT user_id FROM User_Projects WHERE project_number = @project_number)", conn))
                    {
                        com.Parameters.Add("@project_number", Project.project_number);
                        List<string> developerNames = new List<string>();
                        using (SqlDataReader rdrDev = com.ExecuteReader())
                        {
                            if (rdrDev.HasRows)
                            {
                                while (rdrDev.Read())
                                {
                                    developerNames.Add((string)rdrDev["user_name"]);
                                }
                            }
                        }
                        // set names to project object
                        Project.developer_name = string.Join(", ", developerNames);
                    }

                }
        }
        var js = new JavaScriptSerializer();
        Context.Response.Write(js.Serialize(projects));
    }