我有一个在TextChanged事件上的文本框,该文本框允许用户过滤数据网格行。数据表绑定到数据源的数据网格。我还通过数据表将总计行添加到了数据网格,以求和所有行。我想动态地汇总每次过滤中的行。我该如何实现?
private filterTextBox_TextChanged(object sender, EventArgs e)
{
(dgv1.DataSource as DataTable).DefaultView.RowFilter =
string.Format("Name LIKE '%{0}'", textBoxFilter.Text);
}
private string SumColumn(string rowItem)
{
return dataTable.AsEnumerable().Sum(x => decimal.Parse(x[rowItem].ToString(),
System.Globalization.NumberStyles.Currency, null)).ToString("c");
}
private void dgv1_TotalRow()
{
DataRow row = dataTable.NewRow();
row["Amount1"] = SumColumn("Amount1");
row["Amount2"] = SumColumn("Amount2");
row["Amount3"] = SumColumn("Amount3");
row["Amount4"] = SumColumn("Amount4");
dataTable.Rows.Add(row);
}
private void Load_DGV()
{
dgv1_TotalRow();
dgv1.DataSource = dataTable;
}
答案 0 :(得分:0)
private double Sum(DataGridView dgv, string ColumnName)
{
double sum = 0;
foreach(DataGridViewRow row in dgv.Rows)
sum += Convert.ToDouble(row.Cells[ColumnName].Value);
return sum;
}
将此代码添加到该表单中,并在filterTextBox_TextChanged
事件结束时像这样TextBoxWhereYouShowSum.Text = Sum(yourDataGridView, ColumnNameToSum).ToString();