我有DataGridView,其中包含大量数据和搜索文本框。 我的问题是,当我过滤datagridview行时,我想根据搜索数据更改小计标签,但我无法这样做,因为我选择了查询的小计SUM。
这是我的子标签代码
SqlConnection con = new SqlConnection(str);
con.Open();
string query = "SELECT SUM(Sub_Total) from (SELECT distinct Sub_Total FROM Sales_Order) as Sales_Order";
using (SqlCommand command = new SqlCommand(query, con))
{
object result = command.ExecuteScalar();
Sub_Tot.Text = Convert.ToString(result); ;
}
con.Close();
Textbox Textchanged code:
SqlConnection con = new SqlConnection(str);
con.Open();
SqlDataAdapter sda = new SqlDataAdapter("Select Invoice_no,Date_of_Sale,Customer_Name,Contact,Item_Code,Item_Name,Quantity,Selling_Price,Discount,Paid_Amount,Remaining,Sub_Total,Total From Sales_Order Order By Invoice_no", con);
DataTable dt = new DataTable();
sda.Fill(dt);
dgv.DataSource = dt;
DataView dv = new DataView(dt);
dv.RowFilter = string.Format("Item_Name LIKE '{0}%' ", Search_By_ItemName.Text);
dgv.DataSource = dv;
每件事都运行正常,但根据过滤器不改变SubTotal Text 我想根据搜索过滤器更改我的SubTotal标签文本怎么可能?
注意:它使用计时器完美运行,但我不想使用计时器
int sum = 0;
for (int i = 0; i < Sale_Order_Grid.Rows.Count; i++)
{
sum += Convert.ToInt32(Sale_Order_Grid.Rows[i].Cells[8].Value);
}
this.lbl_SubTotal.Text = sum.ToString();
答案 0 :(得分:0)
啊哈,如果我理解正确,你想根据你的搜索查询填写subtotal
标签而不是在你的网格上循环,并逐一对该列求和?是吗?
如果为true,您可以在T-Sql中使用sum聚合并从DataTable
列中获取它,例如:
SqlConnection con = new SqlConnection(str);
con.Open();
SqlDataAdapter sda = new SqlDataAdapter("Select Invoice_no,Date_of_Sale,Customer_Name,Contact,Item_Code,Item_Name,Quantity,Selling_Price,Discount,Paid_Amount,Remaining,Sub_Total,Total,SUM(Sub_Total) as SubTotal From Sales_Order Group by Invoice_no,Date_of_Sale,Customer_Name,Contact,Item_Code,Item_Name,Quantity,Selling_Price,Discount,Paid_Amount,Remaining,Sub_Total,Total Order By Invoice_no", con);
DataTable dt = new DataTable();
sda.Fill(dt);
dgv.DataSource = dt;
DataView dv = new DataView(dt);
dv.RowFilter = string.Format("Item_Name LIKE '{0}%' ", Search_By_ItemName.Text);
dgv.DataSource = dv;
按字段名称获取col值:
var totlaCol= dt.Columns.Cast<DataColumn>().SingleOrDefault(col => col.ColumnName == "SubTotal");
if (totalCol!= null)
{
var tableRows = dt.AsEnumerable().First();
var sumVal= tableRows.Field<string>(totlaCol);
// or
//sumVal = tableRows.Field<string>(dt.Columns.IndexOf(myColumn));
}
1-注意如果您使用Sum
,则应Group by
选择的列。
2-您可以使用单独的查询来选择sum col并使用单独的DataTable
3-之前我没有测试过,但我确定这样可以给你预期的输出。