我有一个WinForms项目,该项目的报表在网格中显示员工数据。我正在尝试计算平均每周工时超过文本框中输入的阈值的员工的百分比。当没有对网格应用筛选时,计算工作正常,但当我根据“代理”或“工作类型”筛选网格时,百分比不正确。
下面是相关代码的一个片段:
// Code to get data and calculate percentage
private HMReportsController ReportController = new HMReportsController(cGlobal.ConnectionString);
private const string ReportHeader = "Average Employee Hours Report";
private int RowCount = 0;
private double HourThreshold = 0;
private double AboveAverageCount = 0;
private double AboveAveragePercentage;
private void button_GetData_Click(object sender, EventArgs e)
{
Cursor.Current = Cursors.WaitCursor;
try
{
averageEmployeeHourModelBindingSource.DataSource = ReportController.GetAverageEmployeeHours(dateEdit_DateFrom.DateTime, dateEdit_DateTo.DateTime);
}
catch (Exception Ex)
{
MessageBox.Show(Ex.Message);
}
Cursor.Current = Cursors.Default;
}
private void buttom_Calculate_Click(object sender, EventArgs e)
{
try
{
// Get the threshold value from the numericTextBox_hours
double threshold = (double)numbericTextBox_Hours.GetNumericValue();
// Calculate the count of people with WeeklyAverage above the threshold
AboveAverageCount = averageEmployeeHourModelBindingSource
.Cast<AverageEmployeeHourModel>()
.Count(item => item.WeeklyAverage.HasValue && item.WeeklyAverage.Value > threshold);
// Calculate the total count of items in the grid
RowCount = averageEmployeeHourModelBindingSource.Count;
// Calculate the percentage
AboveAveragePercentage = (RowCount > 0) ? (AboveAverageCount / RowCount) * 100 : 0;
// Display the percentage in label_Percentage
label_Percentage.Text = $"Percentage above threshold: {AboveAveragePercentage:F2}%";
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
字符串
型号:
public class AverageEmployeeHourModel
{
public int? PayrollID { get; set; }
public double? WeeklyAverage { get; set; }
public string EmployeeName { get; set; }
public string Agency { get; set; }
public int? NumberOfWeeks { get; set; }
public string EmployeeType { get; set; }
}
型
当我过滤代理或代理类型的网格时,问题出现了,计算变得不准确。
我试图通过捕获列过滤器更改来处理这个问题,但是我发现,如果我过滤然后取消过滤一个代理,它不会被重新添加到绑定源。
我如何确保即使在基于Agency或BaseType对网格应用动态过滤时,百分比的计算也是准确的?任何建议或代码示例都将非常感谢。谢谢!
1条答案
按热度按时间lhcgjxsq1#
我通过一个新的模型和过滤器bool解决了我的问题:
字符串
每次更改列的筛选器时,写入新模型:
型
然后,如果有过滤器应用,则使用新模型,如果没有,则使用原始绑定源:
型