Saturday, January 4, 2014

Export / Output asp net gridview output to excel file

If you want to export gridview output to an excel file you can use the following code.
In this example it is done by clicking a button
Requirements
  1. GridView with ID GridView1
  2. ASP NET Button With ID Button1
    protected void Button1_Click(object sender, EventArgs e)
    {
        string filename = "Bingo.xls";
        ExportToExcel(filename, GridView1);
    }
     
    private void ExportToExcel(string filename, GridView gv)
    {
        Response.ClearContent();
        Response.AppendHeader("content-disposition""attachment; filename=" + filename);
        Response.Charset = "";
        Response.Cache.SetCacheability(HttpCacheability.NoCache);
        Response.ContentType = "application/vnd.ms-excel";
        System.IO.StringWriter stringWriter = new System.IO.StringWriter();
        HtmlTextWriter htw = new HtmlTextWriter(stringWriter);
        gv.RenderControl(htw);
        Response.Write(stringWriter.ToString());
        Response.End();
    }
Half way there Don't forget to override VerifyRenderingInServerForm
public override void VerifyRenderingInServerForm(Control control)
{
    /* Verifies that the control is rendered */
}
All done.

Monday, November 25, 2013

How to disable jQuery UI tab(s)

Single tab

$( "#tabs" ).tabs( "option", "disabled", 1);

Multiple tabs

$( "#tabs" ).tabs('option','disabled', [1, 2, 3, 4]);

Saturday, November 9, 2013

An entry with the same key already exists.

Causes:
  • Multiple asp net controls with same ID
  • Mostly occurs inside ListView control 
  • Keep an eye on validator controls. Try to have different id on master and child pages.

Sunday, November 3, 2013

Change an Image while using JCrop

Initialize jCrop
var jcrop_api;
        function InitjCrop() {
            $('#id').Jcrop({  }, function () {
                jcrop_api = this;
            });
        }
To unhook jCrop
jcrop_api.destroy();
To Hook jCrop again
InitjCrop();

Wednesday, October 30, 2013

How do I cancel a Delete in MSSQL SERVER

We use instead of delete trigger's ROLLBACK TRAN to cancel a delete statement CREATE TRIGGER dbo.t__protect__locked__from__delete
ON dbo.table
instead OF DELETE
AS
  BEGIN
      SET nocount ON

      DECLARE @IsLocked BIT,
              @ID       INT

      SELECT @IsLocked = IsLocked,@ID = ID
      FROM   deleted

      IF @IsLocked = 1
        BEGIN
            RAISERROR ('Cannot delete',16,1)
            ROLLBACK TRAN
            RETURN
        END
      -- Go ahead and do the update or some other business rules here
      ELSE
        DELETE FROM table
        WHERE  ( ID = @ID )
  END
GO