在DataGrid列WPF C#中显示数据库表中多少行的COUNT

时间:2019-11-28 16:28:16

标签: c# sql wpf

我一直在努力尝试使用COUNT将我的数据库中有多少行显示到名为“ JobsCount ”的DataGrid列中。

sqlCon.Open();
            string query = "SELECT UserName, COUNT(UserName) as count FROM tblJobs WHERE JobStatus != 'Booked' Group by UserName";
            SqlCommand cmd = new SqlCommand(query, sqlCon);

            using (SqlDataAdapter adapter = new SqlDataAdapter(cmd))
            {
                DataTable dt = new DataTable();

                adapter.Fill(dt);
                tblJobsBooked.ItemsSource = dt.DefaultView;
            }
            sqlCon.Close();

DataGrid列

<DataGrid.Columns>
  <DataGridTextColumn Header="User" Binding="{Binding UserName}"/>
  <DataGridTextColumn Header="Jobs Booked" Binding="{Binding JobsCount}" />
</DataGrid.Columns>

COUNT应该由用户名计算。

1 个答案:

答案 0 :(得分:3)

更改:

string query = "SELECT UserName, COUNT(UserName) as count FROM tblJobs WHERE JobStatus != 'Booked' Group by UserName";

对此:

string query = "SELECT UserName, COUNT(UserName) as JobsCount FROM tblJobs WHERE JobStatus != 'Booked' Group by UserName";

看到区别了吗?除非名称完全匹配,否则DataGrid无法绑定。