我在C#中运行的两个查询是在datagridview中运行的,一个是显示所有数据。另一个设置为在页脚中显示。页脚显示,只是不显示我的查询。 查询一个(带页脚)
protected void Button2_Click(object sender, EventArgs e)
{
MySqlCommand cmd = new MySqlCommand("SELECT * FROM Customer", cs);
cs.Open();
MySqlDataReader dgl = cmd.ExecuteReader();
dg.ShowFooter = true;
dg.DataSource = dgl;
dg.DataBind();
cs.Close();
}
**query two(footer query)**
protected void dg_DataBound(object sender, EventArgs e)
{
MySqlCommand cmd = new MySqlCommand("SELECT SUM(Donation) AS Total_Donation FROM Customer", cs);
cs.Open();
String totalDonations = Convert.ToString(cmd.ExecuteScalar());
cs.Close();
dg.FooterRow.Cells[3].Text = totalDonations;
}
数据网格显示查询效果良好,页脚甚至显示但没有任何数据。
答案 0 :(得分:1)
经过几个小时的问题,我已经解决了。
corrected code
{
MySqlCommand cmd = new MySqlCommand("SELECT * FROM Customer", cs);
MySqlCommand cmdtwo = new MySqlCommand("SELECT SUM(Donation) AS Total_Donation FROM Customer", cs);
cs.Open();
MySqlDataReader dgl = cmd.ExecuteReader();
dg.DataSource = dgl;
dg.ShowFooter = true;
dg.DataBind();
cs.Close();
cs.Open();
string totalDonations = Convert.ToString(cmdtwo.ExecuteScalar());
cs.Close();
dg.FooterRow.Cells[7].Text = "Total £";
dg.FooterRow.Cells[8].Text = totalDonations;
}
虽然我确信有更好的方法可以做到这一点,如果您知道,请随时编辑。
答案 1 :(得分:1)
虽然你有它的工作方式,但仍有办法改进它。
在第一种方法中,using语句可以更好地管理连接:
protected void Button2_Click(object sender, EventArgs e)
{
DataTable dt = new DataTable();
//Assuming you have a connection string strConnect
using (SqlConnection con = new SqlConnection(strConnect))
{
con.Open();
using (SqlDataAdapter da = new SqlDataAdapter("SELECT * FROM Customer", con))
{
da.Fill(dt);
}
}
dg.ShowFooter = true;
dg.DataSource = dt;
dg.DataBind();
}
第二种方法:
protected void dg_DataBound(object sender, EventArgs e)
{
String totalDonations = string.Empty;
//Assuming you have a connection string strConnect
using (SqlConnection con = new SqlConnection(strConnect))
{
con.Open();
using (SqlCommand cmd = new SqlCommand("SELECT SUM(Donation) AS Total_Donation FROM Customer", con))
{
totalDonations = Convert.ToString(cmd.ExecuteScalar());
}
}
dg.FooterRow.Cells[3].Text = totalDonations;
}
我可能会使用GridView的RowDataBound写入页脚,我可以知道行的类型:
protected void dg_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.Footer)
{
String totalDonations = string.Empty;
//Assuming you have a connection string strConnect
using (SqlConnection con = new SqlConnection(strConnect))
{
con.Open();
using (SqlCommand cmd = new SqlCommand("SELECT SUM(Donation) AS Total_Donation FROM Customer", con))
{
totalDonations = Convert.ToString(cmd.ExecuteScalar());
}
}
e.Row.Cells[3].Text = totalDonations;
}
}
编辑:以下是我用来测试的标记:
<asp:GridView ID="dg" runat="server" AutoGenerateColumns="true" OnDataBound="dg_DataBound" ShowFooter="true">
</asp:GridView>