Showing posts with label XML HTTP Response. Show all posts
Showing posts with label XML HTTP Response. Show all posts

Sunday, December 9, 2018

Convert ASP.NET GridView to Excel the right way

This sample VB.NET code over comes following limitations of using the Interop dll:
1. RegisterForEventValidation can only be called during Render https://stackoverflow.com/questions/7228718/registerforeventvalidation-can-only-be-called-during-render
2. GridView must be placed inside a form tag with runat=“server” even after the GridView is within a form tag https://stackoverflow.com/questions/6343630/gridview-must-be-placed-inside-a-form-tag-with-runat-server-even-after-the-gri


Github link: https://github.com/rsk2/export-gridview-to-excel



Wednesday, March 30, 2016

Code to search CSV files and provide user the option to download them

You have some CSV files stored in a folder on your server and you want to let the user download each separately. You will need a ASP.NET placeholder (ID="Downloads") on your UI.

 private void CheckForDownloadFiles(string filePath)
    {
        DirectoryInfo d = new DirectoryInfo(filePath);  
        FileInfo[] Files = d.GetFiles("*.csv"); //Getting CSV files
        Downloads.Controls.Clear();
        string str = ""; int i = 0;
        foreach (FileInfo file in Files)
        {
            str = str + ", " + file.Name;
            i++;
            CreateLinkButtonAndLabel(file.Name,i, filePath);
        }
    }


private void CreateLinkButtonAndLabel(string fileName, int count, string filePath)
    {

        Downloads.Controls.Add(new LiteralControl("<br />"));
        LinkButton newDownload = new LinkButton();
        newDownload.ID = "DownloadBtn"+count;
        newDownload.CommandArgument = filePath+fileName;
        newDownload.Click += new EventHandler(DownloadCSV);
        newDownload.CssClass += "btn btn-success btn-xs";
        newDownload.Text = "<img src='../Images/icons/csv-file.gif' alt='Download CSV File' /> Download CSV";
        Downloads.Controls.Add(newDownload);
        Label label = new Label();
        label.ID = "DownloadLabel" + count;       
        label.Text = " "+fileName+" ";
        Downloads.Controls.Add(label);
}


protected void DownloadCSV(object sender, EventArgs e)
    {

        LinkButton btn = (LinkButton)sender;
        string fullFilePath = btn.CommandArgument;
        if(fileName.Contains("csv"))
            Response.Redirect(fullFilePath);
  }

This will create a button and display the name of your file next to it: