最近在學C#,這對於我這個原本寫VB的人實在是很痛苦,語法差好多呀!最近遇到一個問題,就是將資料呈現在GridView後要顯是加總,於是上網找了一下有類似的範例改寫一下就完成囉!
以下是程式碼,紅色字體的部分就是囉!
protected void Button1_Click(object sender, EventArgs e)
{
StringBuilder sbSql = new StringBuilder();
sbSql.Append("SELECT start_time,ani,phone_number,duration,total_units ");
sbSql.Append("FROM billingrecorduser ");
sbSql.Append("ORDER BY start_time");
db_conn connectdb = new db_conn();
SqlConnection oConn = connectdb.opendb("db201");
SqlCommand cmd = new SqlCommand(sbSql.ToString() , oConn);
try
{
oConn.Open();
SqlDataReader dr = cmd.ExecuteReader();
DataTable dt = new DataTable();
dt.Clear();
for (int i = 0; i <= dr.FieldCount - 1; i++)
{
DataColumn col = new DataColumn();
col.ColumnName = dr.GetName(i);
col.DataType = dr.GetFieldType(i);
dt.Columns.Add(col);
}
float nTotalDuration = 0;
float nTotalUnits = 0;
while (dr.Read())
{
DataRow row = dt.NewRow();
for (int j = 0; j <= dr.FieldCount - 1; j++)
{
row[j] = dr.GetValue(j);
if (j == 3)
{
nTotalDuration = nTotalDuration + Convert.ToSingle(dr.GetSqlValue(j).ToString());
}
if (j == 4)
{
nTotalUnits = nTotalUnits + Convert.ToSingle(dr.GetSqlValue(j).ToString());
}
}
dt.Rows.Add(row);
}
GridView1.DataSource = dt;
GridView1.DataBind();
GridView1.FooterRow.Cells[2].Text = "Total:";
GridView1.FooterRow.Cells[3].Text = nTotalDuration.ToString() ;
GridView1.FooterRow.Cells[4].Text = nTotalUnits.ToString();
dr.Close();
oConn.Close();
}
catch (Exception ex)
{
Response.Write(ex.Message);
}
}
呈現的方式如下
留言列表