C# DataGridView添加合计行

不废话,代码示例如下

C# DataGridView添加合计行_第1张图片


string strcon = "Integrated Security=SSPI;Persist Security Info=False;Initial Catalog=employee;Data Source=(local)";
            string strsql="select * from class";
            private DataTable dtshowdata()
            {
                SqlConnection con = new SqlConnection(strcon );
                SqlCommand cmd = new SqlCommand(strsql ,con);
                con.Open();
                SqlDataAdapter da = new SqlDataAdapter(cmd);
                DataTable dt = new DataTable();
                da.Fill(dt);
                GC.Collect();
                con.Close();
                return dt;
            }


            private DataTable dtstaticdata()
            {
                DataTable dt = dtshowdata();
                DataRow dr = dt.NewRow();
                dr[0] = "统计";
                dr[1] = dt.Compute("Sum(语文)", null);//无效的聚合函数 Sum()和类型 String 的用法 数据库中的数据类型必须是数字
                dr[2] = dt.Compute("Sum(数学)",null);//求平均数avg;
                dt.Rows.Add(dr);
                return dt;
            }

            private void Smot() //锁定统计行 不让排序
            {
                for (int i = 0; i <=dataGridView2.Columns.Count - 1; i++)//如果想让统计置顶 可以去掉=号;就可以选择置顶
                {
                    dataGridView2.Columns[i].SortMode = DataGridViewColumnSortMode.NotSortable;
                }
            }
            private void button2_Click(object sender, EventArgs e)
            {
                this.dataGridView2.DataSource = dtshowdata();
            }

            private void button3_Click(object sender, EventArgs e)
            {
                this.dataGridView2.DataSource = dtstaticdata();
                Smot();
                dataGridView2.Rows[dataGridView2.Rows.Count - 1].DefaultCellStyle.BackColor = Color.Red;
            }



你可能感兴趣的:(C#.net,C#控件(treeview,comboBox,datagridview))