Tuesday, September 27, 2016

Export ASPX GridView control to Excel

GridView control in aspx page
Report.aspx
<asp:Button ID="btnExport" runat="server" Text="Export To Excel" OnClick ="btnExport_Click" />
            <br /><br />
            <asp:GridView ID="GridView1" PageSize="5" AllowPaging="True" DataKeyField="PSID" OnRowDataBound="RowDataBound" AutoGenerateColumns="False" runat="server">
                <Columns>
                    <asp:BoundField DataField="PSID" HeaderText="PSID" SortExpression="PSID"></asp:BoundField>
                    <asp:BoundField DataField="Name" HeaderText="Name" SortExpression="Name"></asp:BoundField>
                    <asp:BoundField DataField="Email" HeaderText="Email" SortExpression="Email"></asp:BoundField>
                    <asp:BoundField DataField="Area" HeaderText="Area" SortExpression="Area"></asp:BoundField>
                    <asp:BoundField DataField="Department" HeaderText="Department" SortExpression="Department"></asp:BoundField>               
                    <asp:BoundField DataField="Attempted" HeaderText="No of Attemped" SortExpression="Attempted"></asp:BoundField>
                    <asp:BoundField DataField="AcceptedStatus" HeaderText="Status" SortExpression="AcceptedStatus"></asp:BoundField>
                </Columns>
            </asp:GridView>


Report.aspx.cs

 protected void Page_Load(object sender, EventArgs e)
        {

            using (SqlConnection con = new SqlConnection(conString))
            {

             if(!IsPostBack){
                 Status.Items.Add(new ListItem("All Status", ""));
                Status.Items.Add(new ListItem("Accepted", "1"));
                Status.Items.Add(new ListItem("Decline", "0"));
               }


                using (SqlCommand cmd = new SqlCommand("SELECT * FROM TBL_TRN_REPORT", con))
                {
                    cmd.CommandType = CommandType.Text;
                    using (SqlDataAdapter sda = new SqlDataAdapter(cmd))
                    {
                        using (DataTable dt = new DataTable())
                        {
                            sda.Fill(dt);
                            GridView1.DataSource = dt;
                            GridView1.DataBind();
                        }
                    }
                }
            }
        }

 protected void btnExport_Click(object sender, EventArgs e)
        {
            Response.Clear();
            Response.Buffer = true;
            Response.AddHeader("content-disposition", "attachment;filename=GridViewExport.xlsx");
            Response.Charset = "";
            Response.ContentType = "application/vnd.ms-excel";
            StringWriter sw = new StringWriter();
            HtmlTextWriter hw = new HtmlTextWriter(sw);
            GridView1.RenderControl(hw);
            Response.Write(sw.ToString());
            Response.End();
           
        }

        public override void VerifyRenderingInServerForm(Control control)
        {
            //It solves the error "Control 'GridView1' of type 'GridView' must be placed inside a form tag with runat=server."
        }

Friday, January 1, 2016

Ajax Call from Web form application

Hi,
I had a problem while i trying to submit variable value with dynamic button control.
The example was like

<% foreach(int productId in products){ %>
<asp:Button ID="Button2" onclick="callfunction" 
CommandArgument="<%= productId %>" runat="server" Text="Button" />
<% }?>

But i found it's not working because of control value will not assign after page_load. Then i try to do it with AJAX

I have change the Button control with HTML Button

<% foreach(int productId in products){ %>
 <input id="Button1" onclick="AddtoCartItems(<%=product.ProductId %>)" type="button" value="Add To Cart" /> 
<% }?>

After that i have written the following ajax code.

<script type="text/javascript">            
       function AddtoCartItems(pid) {    
                 $.ajax({
                     url: 'AddToCart.aspx/GetData',
                     type: "POST",
                     dataType: "json",
                     data: "{'name': '" + pid + "'}",
                     contentType: "application/json; charset=utf-8",
                     success: function (data) {
                         alert(JSON.stringify(data));
                     }
             });
       }
    </script>


Now i have create AddToCart.aspx With GetData Methord

using System.Web.Services;
using Newtonsoft.Json;


[WebMethod]
        public static string GetData(string name)
        {
           --------Your code here-----------

           return "Success";
        }


2 more thing you need to do.
Go to App_Start/RouteConfig.cs 
Change 
settings.AutoRedirectMode = RedirectMode.Permanent;       
           TO
settings.AutoRedirectMode = RedirectMode.Off;

Same As go to Web.config and add the following line
<system.web>
  ... 
    <webServices>
        <protocols>
            <add name="HttpGet"/>
            <add name="HttpPost"/>
        </protocols>
    </webServices>
    <authorization>
      <allow users="*"/>
    </authorization>
 
  </system.web>


That's it. Now you can call your AJAX method successfully.