我正在开发一个具有小型报告服务的简单系统。报表服务一般是一个 DropDownList,根据 DropDownList 的值生成一个 Gridview。在此 GridView 下有一个 ImageButton 用于将 GridView 打印为 Word 文档。我现在的问题是:那个按钮一直出现。它应该与 GridView 一起出现,因为它与之相关。那么该怎么做呢?
ASP.NET 代码:
<div>
<asp:DropDownList ID="DropDownList1" runat="server" AutoPostBack="true"
DataSourceID="SqlDataSource2" DataTextField="Title" DataValueField="ID" OnSelectedIndexChanged="DropDownList1_SelectedIndexChanged">
</asp:DropDownList>
<asp:SqlDataSource ID="SqlDataSource2" runat="server"
ConnectionString="<%$ ConnectionStrings:PM_RegistrationSysDBConnectionString %>"
SelectCommand="SELECT [ID], [Title] FROM [Events]"></asp:SqlDataSource>
</div>
<br />
<div>
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" ShowFooter="true">
<Columns>
<asp:BoundField DataField="Title" HeaderText="Title" SortExpression="Title" />
<asp:BoundField DataField="Name" HeaderText="Name" SortExpression="Name" />
<%--<asp:TemplateField>
<FooterTemplate>
<asp:ImageButton ID="wordBtn" CssClass="icon" runat="server" ImageUrl="images/word.png"
ToolTip="Generate a Word Document" OnClick="creat_word_table"></asp:ImageButton>
</FooterTemplate>
</asp:TemplateField>--%>
</Columns>
</asp:GridView>
<br />
<asp:ImageButton ID="wordBtn" CssClass="icon" runat="server" ImageUrl="images/word.png"
ToolTip="Generate a Word Document" OnClick="creat_word_table"></asp:ImageButton>
</div>
C#代码:
protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)
{
string connString = ConfigurationManager.ConnectionStrings["PM_RegistrationSysDBConnectionString"].ConnectionString;
SqlConnection conn = new SqlConnection(connString);
string eventTitle = DropDownList1.SelectedItem.Text;
string cmd = @"SELECT dbo.Events.Title, dbo.Users.Name
FROM dbo.BookingDetails INNER JOIN
dbo.Events ON dbo.BookingDetails.EventID = dbo.Events.ID INNER JOIN
dbo.Users ON dbo.BookingDetails.NetworkID = dbo.Users.NetworkID
WHERE (dbo.Events.IsActive = 1) AND (dbo.Events.Title = '"+eventTitle+"')";
SqlDataAdapter da = new SqlDataAdapter(cmd, conn);
DataTable dt = new DataTable();
da.Fill(dt);
GridView1.DataSource = dt;
GridView1.DataBind();
}
public void creat_word_table(object sender, EventArgs e)
{
Response.AddHeader("content-disposition", "attachment;filename=Export.doc");
Response.Cache.SetCacheability(HttpCacheability.NoCache);
Response.ContentType = "application/vnd.word";
StringWriter stringWrite = new StringWriter();
HtmlTextWriter htmlWrite = new HtmlTextWriter(stringWrite);
HtmlForm frm = new HtmlForm();
GridView1.Parent.Controls.Add(frm);
frm.Attributes["runat"] = "server";
frm.Controls.Add(GridView1);
frm.RenderControl(htmlWrite);
Response.Write(stringWrite.ToString());
Response.End();
}