Thursday, 20 September 2012

Validation of viewstate MAC failed

Generate machine key 

Introduction

Whenever you make use of ViewState, Session, Forms authentication, or other encrypted and/or secured values, ASP.NET uses a set of keys to do the encryption and decryption. Normally, these keys are hidden and automatically generated by ASP.NET every time your application recycles, but there are times when you want to specify a particular, persistent key. This article will explain why hard-coded machineKeys are good, and how to generate random ones for ASP.NET 1.1 or 2.0.

Why you Want a Persistent Key

There are two keys that ASP.NET uses to encrypt, decrypt, and validate data in ViewState, Forms Authetication tickets, and out-of-process Session data. The decryptionKey is used for encryption and decryption of authentication tickets and encrypted ViewState information. The validationKey is used to validate ViewState and ensure it hasn't been tampered with, and generate unique application-specific session IDs for out-of-process session storage.
You can run into problems if the key changes between postbacks, e.g., if the keys used to generate the ViewState information are different from one page to the next. If that happens, the ViewState validation will fail (because the validationKey after postback will be different from what was used pre-postback) and the user will get an Invalid_ViewState error. Different keys across postback can also mean that your Forms Authentication tickets will fail, requiring users to log back into your application; out-of-process session information will be lost (since the session IDs will change); and encrypted ViewState information will be unable to be decrypted and read.
Lastly, if you want to use encrypted passwords with ASP.NET 2.0's Membership provider, you have to provide a static key, or else you'll get a You must specify a non-autogenerated machine key to store passwords in the encrypted format error.

Why Would the Key Change?

Keys can change across postbacks more often than you'd expect. One way is if you're running a web farm. By default, the validationKey used to create the MAC is randomly generated by ASP.NET when the application pool starts up. This ensures that the validation key is unique and changes periodically. However, since the key is different from server to server, if you're viewing a page on Server A and post it to Server B, when Server B generates a MAC based on the viewstate data, that value won't match the MAC value when the page was initially served by Server A. Thus, you'll get an Invalid_Viewstate error.
Another reason the validationKey and decryptionKey (and thus the MAC) will be different is if you cross application pools. If you view a page running in pool A, and post to another page on pool B (e.g., through Server.Transfer), the keys will be different & you'll get a mismatch.
Lastly, the validationKey and decryptionKey can change mid-session for users if the application pool restarts. Assume some user is viewing a page on your site and filling out a form. While they're doing that, some sysadmin restarts the pool, thus generating a new key. When the user posts the page, they'll get an Invalid_Viewstate error. The application can also restart if it is set to shut down while idle (the default is to shut down pools that have been idle for 20 minutes). Imagine a user who views a page on your site, goes away for 10 minutes, then maybe spends 20 minutes filling in the form on the page. Meanwhile, no one else is on your site, so the application pool times out & shuts down. When the user finally posts the form (30 minutes after viewing it), the application pool will start back up, create a new validation key, generate a new MAC, notice that the MAC values don't match, and reward your user's diligence with an Invalid_Viewstate error.

Where to Put the Key

So if you want to create a static set of keys, you'll need to put it in the machineKey block in either the machine.config or web.config. You can read more about the machineKey element on MSDN.
The validationKeys are a maximum of 64 bytes long. In ASP.NET 1.1, the encryption algorithm was 3DES along with a maximum 24 byte decryptionKey. ASP.NET 2.0 provided an attribute called decryption allowing the user to specify the hashing algorithm used for decrypting data. The AES algorithm is the best choice, and accommodates a 32 byte decryptionKey.

<machineKey
validationKey="794133024E0693ADB7FA3796A94F845B29A7516E317B371119B389F9E3F822D3B97BE5B0CE0E0C15135772BA29B65D9E23985B88AD746B375128C7FD8A0EC685"
decryptionKey="6E49304B3439D1F6037794D6372C26306D158F1CD07B3039305288DB344797E0"
validation="SHA1" decryption="AES"
/>

Tuesday, 18 September 2012

'Sys' is undefined error in visual studio 2005

 <system.web>
 <httpHandlers>
<add  verb="GET,HEAD" path="ScriptResource.axd" type="System.Web.Handlers.ScriptResourceHandler, System.Web.Extensions, Version=1.0.61025.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" />


add this in web config.

Tuesday, 4 September 2012

View and Update XML using C#

This is complete project

How will it works.
1) This code contain master page so just remove it if u don't need.
2) All the xml files will show in a Table  in page XmlFiles.aspx.
3) Select File that you want to open.after selection selected file will open in page 2.
4) System.Configuration.ConfigurationManager.AppSettings["configFiles"] contain folder path where xml files exist.


This page will show all xml files in a table.

.aspx page


<%@ Page Language="C#" MasterPageFile="~/AuditMaster.master" AutoEventWireup="true"
    CodeFile="XmlFiles.aspx.cs" Inherits="Admin_XmlFiles" Title="Untitled Page" %>

<asp:Content ID="Content1" ContentPlaceHolderID="ContentPlaceHolder1" runat="Server">
    <div id="contener">
        <div>
            <span style="color: #ff99ff">
                <br />
                <span style="color:Blue">List of Availble XML files :<br />
                    <br />
                </span></span>
        </div>
        <table border="1" style="font-size: 12pt">
            <tr>
                <th style=" font-size:10pt">
                    Serial No.</th>
                <th style=" font-size:10pt">
                    File Name</th>
            </tr>
            <%int i = 0; %>
            <%foreach (System.IO.FileInfo fi in rgFiles)
              {%>
            <tr>
                <td style=" font-size:10pt">
                    <%=++i%>
                </td>
                <td style=" font-size:10pt">
                    <a href="ServiceDashboardManager.aspx?fileName=<%=fi.Name %>">
                        <%=fi.Name%>
                    </a>
                </td>
            </tr>
            <%} %>
        </table>
    </div>
</asp:Content>


.Cs Page

using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.IO;
using TboCommon;
public partial class Admin_XmlFiles : System.Web.UI.Page
{
    protected FileInfo[] rgFiles = new FileInfo[0];
    protected void Page_Load(object sender, EventArgs e)
    {
      
     
        Page.Title = "View XML files";
        string configPath = System.Configuration.ConfigurationManager.AppSettings["configFiles"];
        DirectoryInfo di = new DirectoryInfo(configPath);
        rgFiles = di.GetFiles("*.xml");
    }
  
}

Page 2--------after click on xml file of first page this page will open.

.aspx page


<%@ Page Language="C#" MasterPageFile="~/AuditMaster.master" AutoEventWireup="true"
    CodeFile="ServiceDashboardManager.aspx.cs" Inherits="Admin_ServiceDashboardManager"
    Title="Untitled Page" %>
<asp:Content ID="Content1" ContentPlaceHolderID="ContentPlaceHolder1" runat="Server">
    <div id="contener">
        <div style="margin-top: 20px; margin-left: 5px;">
            <asp:XmlDataSource ID="XmlDataSource1" runat="server" />
            <asp:TreeView ID="treeView1" ExpandDepth="3" MaxDataBindDepth="3" runat="server">
            </asp:TreeView>
            <div style="margin-top: 10px;">
                <asp:Button ID="Save" runat="server" Text="Save" OnClick="Save_Click" />
                <asp:Label ID="lblMessage" runat="server"></asp:Label>
            </div>
        </div>
    </div>
</asp:Content>


.cs page

using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Xml;
using System.IO;
using TboCommon;

public partial class Admin_ServiceDashboardManager : System.Web.UI.Page,IAuthentication
{
    protected string fileName = string.Empty;
    protected string physicalPath = ConfigurationManager.AppSettings["configFiles"];
    string applicationname = string.Empty;
    protected XmlTextReader reader;
    protected XmlNodeType nType = new XmlNodeType();
    int counter = 0;
    int tempcount = 0;
    static StreamWriter sr;
    protected string errorMessage = string.Empty;
    XmlDocument doc;
    int memberId = 0;
    string fullPath = string.Empty;
    protected FileInfo[] rgFiles = new FileInfo[0];
    protected void Page_Load(object sender, EventArgs e)
    {
        
        Page.Title = "Update XML file";
        string configPath = System.Configuration.ConfigurationManager.AppSettings["configFiles"];
        DirectoryInfo di = new DirectoryInfo(configPath);
        string s = Convert.ToString(Request.QueryString["fileName"]);
      
        if (s != null && s.Length > 2)
        {
            fileName = s;
            showxml(fileName);
        }
        else
        {

        }
      
    }
    void showxml(string fileName)
    {
        fullPath = physicalPath + fileName;
        XmlDataSource1.DataFile = fullPath;
        try
        {
            treeView1.Nodes.Clear();
            //  Loads the  XML document
            reader = new XmlTextReader(fullPath);
            doc = new XmlDocument();
            doc.Load(fullPath);

            // Adds the root to the treeview         
            treeView1.Nodes.Add(new TreeNode(doc.DocumentElement.Name));
            TreeNode tNode = new TreeNode();
            tNode = treeView1.Nodes[0];
            // Adds remainings nodes to the tree view
            AddNode(doc.DocumentElement, tNode);
            //  collpasing all the Nodes.
            treeView1.CollapseAll();
        }
        catch (XmlException xmlEx)
        {
            string IPAddr = Request.ServerVariables["REMOTE_ADDR"];
            Response.Write(xmlEx.Message);
        }
        catch (Exception ex)
        {
            string IPAddr = Request.ServerVariables["REMOTE_ADDR"];
            Response.Write(ex.Message);
        }
    }


    /// <summary>
    /// This Method will add a node recursively and construct Tree View
    /// </summary>
    /// <param name="inXmlNode"></param>
    /// <param name="inTreeNode"></param>
    private void AddNode(XmlNode inXmlNode, TreeNode inTreeNode)
    {
        XmlNode xNode;
        TreeNode tNode;
        XmlNodeList nodeList;
        int i;
        HtmlInputText tempText = new HtmlInputText();
        //  If it is having child nodes then it will add them recursively        
        if (inXmlNode.HasChildNodes)
        {
            nodeList = inXmlNode.ChildNodes;
            for (i = 0; i <= nodeList.Count - 1; i++)
            {
                xNode = inXmlNode.ChildNodes[i];
                inTreeNode.ChildNodes.Add(new TreeNode(xNode.Name));

                tNode = inTreeNode.ChildNodes[i];
                AddNode(xNode, tNode);
            }

        }
        else if (inXmlNode.InnerText.Equals(""))
        {
            //  If the element doesnt contain any data Item then display empty Text Box
            inTreeNode.ChildNodes.Add(new TreeNode(inXmlNode.Name));
            inTreeNode.ChildNodes[0].Text = "<input type='text' name='" + counter + "' value=''>";
            counter++;
        }
        else
        {     // if it is Data then display it in Text box.       
            inTreeNode.Text = "<input type='text' name='" + counter + "' value='" + (inXmlNode.OuterXml.Trim()) + "'>";
            counter++;
        }
    }

    /// <summary>
    /// This method will update the XML when user saves the  data.
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    protected void Save_Click(object sender, EventArgs e)
    {
        if (IsPostBack)
        {
            TreeNode tNode = new TreeNode();
            tNode = treeView1.Nodes[0];
            exportToXml(treeView1, fullPath);
        }
        Response.Redirect("ServiceDashboardManager.aspx?fileName=" + fileName);
    }
    string str = string.Empty;
    /// <summary>
    /// This method will overwrites the existing XML 
    /// </summary>
    /// <param name="tv"></param>
    /// <param name="filename"></param>
    public void exportToXml(TreeView tv, string fullPath)
    {
        sr = new StreamWriter(fullPath, false, System.Text.Encoding.UTF8);
        sr.WriteLine("<?xml version=\"1.0\" encoding=\"utf-8\" ?>");

        IEnumerator ie = tv.Nodes.GetEnumerator();
        if (ie.MoveNext())
        {
            TreeNode tn = (TreeNode)ie.Current;
            sr.WriteLine("<" + tn.Text + ">");
            parseNode(tn);
        }

        sr.Close();
    }
    /// <summary>
    /// This Method will update the XML file recursively.
    /// </summary>
    /// <param name="tn"></param>
    private void parseNode(TreeNode tn)
    {
        IEnumerator ie = tn.ChildNodes.GetEnumerator();

        string parentnode = "";
        int flag = 0;
        parentnode = tn.Text;

        while (ie.MoveNext())
        {
            TreeNode ctn = (TreeNode)ie.Current;
            // if it is element write it in file.
            if (ctn.ChildNodes.Count != 0)
            {
                sr.Write("<" + ctn.Text + ">");
            }
            // if it is data item then get the latest info from text boxes
            if (ctn.ChildNodes.Count == 0 && flag == 0)
            {
                string count = tempcount.ToString();
                string value = Request[count];
                sr.Write(value);
                tempcount++;

            }
            flag = 1;
            // if it is having child nodes then add them recursively
            if (ctn.ChildNodes.Count > 0)
            {
                parseNode(ctn);
            }
        }
        sr.Write("</" + parentnode + ">");
        sr.WriteLine("");
    }
   
}






Monday, 3 September 2012

Export Datatable,Containing XMLData in a column, to CSV using C#


 protected void Button1_ServerClick(object sender, EventArgs e)
    {
        DataTable dtnew = null;
        try
        {
            string filename = "Detail.csv";      

            dtnew = YourDataTable.DefaultView.ToTable();

     // if column detail of YourDataTable contain xml data then

            if (dtnew != null && dtnew.Rows.Count > 0)
            {
                foreach (DataRow dr in dtnew.Rows)
                {
                    dr["detail"] = Common.MyCStr(dr["detail"]).Replace("<", "&lt;");
                    dr["detail"] = Common.MyCStr(dr["detail"]).Replace(">", "&gt;");
                    dr["detail"] = Common.MyCStr(dr["detail"]).Replace(Environment.NewLine,"");
                    dr["detail"] = Common.MyCStr(dr["detail"]).Replace("\n", "");
                }
            }
            string csv = ToCSV(dtnew);
            Response.AddHeader("Content-Disposition", "attachment; filename=" + filename + "");
            Response.AddHeader("Content-Length", csv.Length.ToString());
            Response.Write(csv);
            Response.End();
        }
        catch (OutOfMemoryException oex)
        {
            lblError.Text = "Sorry!Data is too large to export";
        }
        catch (Exception ex)
        {
            lblError.Text = ex.Message;
        }
    }

    public static string ToCSV(DataTable table)
    {
        StringBuilder result = new StringBuilder();
        for (int i = 0; i < table.Columns.Count; i++)
        {
            result.Append(table.Columns[i].ColumnName);
            result.Append(i == table.Columns.Count - 1 ? "\n" : ",");
        }

        foreach (DataRow row in table.Rows)
        {
            for (int i = 0; i < table.Columns.Count; i++)
            {
                result.Append(row[i].ToString());
                result.Append(i == table.Columns.Count - 1 ? "\n" : ",");
            }
        }

        return result.ToString();
    }

Export Datatable to CSV using C#


 protected void Button1_ServerClick(object sender, EventArgs e)
    {
        DataTable dtnew = null;
        try
        {
            string filename = "Detail.csv";         

            dtnew = YourDataTable;         
            string csv = ToCSV(dtnew);
            Response.AddHeader("Content-Disposition", "attachment; filename=" + filename + "");
            Response.AddHeader("Content-Length", csv.Length.ToString());
            Response.Write(csv);
            Response.End();         
        }
        catch (OutOfMemoryException oex)
        {
            lblError.Text = "Sorry!Data is too large to export";
        }
        catch (Exception ex)
        {
            lblError.Text = ex.Message;
        }
    }

    public static string ToCSV(DataTable table)
    {
        StringBuilder result = new StringBuilder();
        for (int i = 0; i < table.Columns.Count; i++)
        {
            result.Append(table.Columns[i].ColumnName);
            result.Append(i == table.Columns.Count - 1 ? "\n" : ",");
        }

        foreach (DataRow row in table.Rows)
        {
            for (int i = 0; i < table.Columns.Count; i++)
            {
                result.Append(row[i].ToString());
                result.Append(i == table.Columns.Count - 1 ? "\n" : ",");
            }
        }

        return result.ToString();
    }

Export Datatable to Excel using C#


  protected void Button1_ServerClick(object sender, EventArgs e)
    {
        DataTable dtnew = null;
        try
        {
            string filename = "Detail.csv";
            System.IO.StringWriter tw = new System.IO.StringWriter();
            System.Web.UI.HtmlTextWriter hw = new System.Web.UI.HtmlTextWriter(tw);
            DataGrid dgGrid = new DataGrid();
            dtnew = YourDataTable; 
            dgGrid.DataSource = dtnew;
            dgGrid.DataBind();
            dgGrid.RenderControl(hw);
            Response.ContentType = "application/vnd.ms-excel";
            Response.AppendHeader("Content-Disposition", "attachment; filename=" + filename + "");
            this.EnableViewState = false;
            Response.Write(tw.ToString());
            Response.End();
        }
        catch (OutOfMemoryException oex)
        {
            lblError.Text = "Sorry!Data is too large to export";
        }
        catch (Exception ex)
        {
            lblError.Text = ex.Message;
        }
    }

 

Read excel using C#,Update excel using C#,Display Excel in html table using c#

.CS Page. 

This is complete project

How will it works.
1) browse any xls and xlsx file and upload it.
2) All the uploaded files will show in a Table.
3) Select File that you want to open.after selection all the sheets of selected table will show.
4) Click on sheet name that u want to open.
5) Data of selected sheet will display in html table.
6) If u wanat to edit excel file u must add ID column in your Excel sheet this column must be numeric and unique.

may be u face some html or css issue in this project,just remove link of non existing css and jscript file.
may be u r unable to create connection with excel just go to following link and install access database engine.
http://www.microsoft.com/en-us/download/details.aspx?id=23734


using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.IO;
using System.Data.OleDb;

public partial class ProductionIssueStatus : System.Web.UI.Page
{
    public DataSet dsSheets = null;
    //public DataTable dt = null;
    public DataTable dtSheeet = null;
    public bool isshowSheet = false;
    protected FileInfo[] rgFiles = new FileInfo[0];

    public System.Data.DataSet xlsInsert(string pth)
    {
        DataSet ds = new DataSet();
        string strcon = string.Empty;
        if (Path.GetExtension(pth).ToLower().Equals(".xls") ||
            Path.GetExtension(pth).ToLower().Equals(".xlsx"))
        {
            strcon = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + pth + ";Extended Properties=\"Excel 12.0;HDR=YES;\"";
            //strcon = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + pth + ";Extended Properties=\"Excel 8.0;HDR=YES;\"";
        }
        else
        {
            strcon = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + pth + ";Extended Properties=\"Excel 12.0;HDR=YES;\"";
        }

        string strselect = "";
        DataTable exDT = new DataTable();
        exDT.TableName = "aa";
        using (OleDbConnection excelCon = new OleDbConnection(strcon))
        {
            try
            {
                DataTable dtSheets = null;
                DataTable dtnew = null;
                excelCon.Open();
                DataTable dtschema = excelCon.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null);
                foreach (DataRow dr in dtschema.Rows)
                {
                    if (!(Convert.ToString(dr["TABLE_NAME"]).IndexOf("FilterDatabase") > 0))
                    {
                        dtSheets = new DataTable();
                        dtSheets.TableName = dr["TABLE_NAME"].ToString();
                        strselect = "Select * from [" + dr["TABLE_NAME"].ToString() + "]";
                        using (OleDbDataAdapter exDA = new OleDbDataAdapter(strselect, excelCon))
                        {
                            exDA.Fill(dtSheets);

                            if (dtSheets.Rows.Count > 0)
                            {

                                dtnew = dtSheets.Clone();
                                if (dtnew.Columns.Contains("Created Time"))
                                {
                                    dtnew.Columns["Created Time"].DataType = typeof(DateTime);
                                    foreach (DataRow drnew in dtSheets.Rows)
                                    {
                                        dtnew.ImportRow(drnew);
                                    }
                                    DataView dv = dtnew.DefaultView;
                                    dv.Sort = "Created Time DESC";
                                    dtSheets = dv.ToTable();
                                }
                                else if (dtnew.Columns.Contains("CreatedTime"))
                                {
                                    dtnew.Columns["CreatedTime"].DataType = typeof(DateTime);
                                    foreach (DataRow drnew in dtSheets.Rows)
                                    {
                                        dtnew.ImportRow(drnew);
                                    }
                                    DataView dv = dtnew.DefaultView;
                                    dv.Sort = "CreatedTime DESC";
                                    dtSheets = dv.ToTable();
                                }

                            }

                        }
                        if (dtSheets != null && dtSheets.Rows.Count > 0)
                        {
                            ds.Tables.Add(dtSheets);
                        }
                    }                

                }
            }
            catch (OleDbException oledb)
            {
                throw new Exception(oledb.Message.ToString());
            }
            catch (Exception ex)
            {
                throw new Exception(ex.Message.ToString());
            }
            finally
            {
                excelCon.Close();
            }          
            if (ds == null || !(ds.Tables.Count > 0))
            {
                throw new Exception("File uploaded has no record found.");
            }
            foreach (DataTable dt in ds.Tables)
            {
                string name = dt.TableName;
            }
            return ds;
        }
    }
    protected void Page_Load(object sender, EventArgs e)
    {
        Page.Title = "Production Support Issue Status";
        if (!IsPostBack)
        {
            ddlColumn.Items.Add("Select");
        }
        if (IsPostBack)
        {
            if (Request.Params.ToString().IndexOf("btnUpdate") > 0)
            {
                if (UpdateData())
                {
                    txtSNo.Value = "";
                    txtNewValue.Value = "";
                    string strScript = "";
                    strScript = "<script>";
                    strScript += "alert('Data Updated successfully');";
                    strScript += "</script>";
                    Page.RegisterStartupScript("strScript", strScript);
                }
                else
                {
                    txtSNo.Value = "";
                    txtNewValue.Value = "";
                    string strScript = "";
                    strScript = "<script>";
                    strScript += "alert('Id does not exist');";
                    strScript += "</script>";
                    Page.RegisterStartupScript("strScript", strScript);
                }
            }
        }
        int isRemove = 0;
        string SheetName = "";    
        string path = Server.MapPath("~/XlsUploadFile");
        DirectoryInfo di = new DirectoryInfo(path);
        rgFiles = di.GetFiles();
        string filename = Convert.ToString(Request.QueryString["fileName"]);
        SheetName = Convert.ToString(Request.QueryString["SheetName"]);
        if (SheetName != null && SheetName.Length > 0)
        {
            isshowSheet = true;
            filename = Convert.ToString(Session["CurrentFile"]);
        }
        Session["CurrentFile"] = filename;
        isRemove = Convert.ToInt32(Request.QueryString["Remove"]);
        if (filename != null && filename != "" && isRemove != 1)
        {
            lblSelectedFile.Text = filename;
            lblSelectedFile.Font.Bold = true;
            string uploadedFile = (Server.MapPath("~/XlsUploadFile/" + filename));
            try
            {
                dsSheets = xlsInsert(uploadedFile);
                if (isshowSheet)
                {
                    dtSheeet = dsSheets.Tables[SheetName];
                }
                ddlColumn.DataSource = getColumnList(dtSheeet);
                ddlColumn.DataTextField = "ColumnName";
                ddlColumn.DataValueField = "ColumnName";
                ddlColumn.DataBind();
                // EditableGrid();
            }
            catch (Exception)
            {
                //uplod = false;
                this.lblMessage.Text = "System uploading Error";
            }
        }
        if (isRemove == 1 && filename != null && filename != "")
        {
            File.Delete(Server.MapPath("~/XlsUploadFile/" + filename));
            Response.Redirect("ProductionIssueStatus.aspx");
        }
    }
    private DataTable getColumnList(DataTable dtSheeet)
    {
        DataTable dt = new DataTable();
        dt.Columns.Add("ColumnName", typeof(string));
        DataRow dr;
        if (dtSheeet != null && dtSheeet.Rows.Count > 0)
        {
            dr = dt.NewRow();
            dr["ColumnName"] = "Select";
            dt.Rows.Add(dr);
            for (int i = 0; i < dtSheeet.Columns.Count; i++)
            {
                dr = dt.NewRow();
                dr["ColumnName"] = dtSheeet.Columns[i].ColumnName;
                dt.Rows.Add(dr);
            }
            return dt;
        }
        else
        {
            dr = dt.NewRow();
            dr["ColumnName"] = "Select";
            dt.Rows.Add(dr);
            return dt;
        }
    }
    protected void btnUpload_Click(object sender, EventArgs e)
    {
        if (xlsUpload.HasFile)
        {
            bool uplod = true;
            string fleUpload = Path.GetExtension(xlsUpload.FileName.ToString());
            if (fleUpload.Trim().ToLower() == ".xls" || fleUpload.Trim().ToLower() == ".xlsx")
            {
                // Save excel file into Server sub dir
                // to catch excel file downloading permission
                if (File.Exists(Server.MapPath("~/XlsUploadFile/" + xlsUpload.FileName.ToString())))
                {
                    File.Delete(Server.MapPath("~/XlsUploadFile/" + xlsUpload.FileName.ToString()));
                }
                xlsUpload.SaveAs(Server.MapPath("~/XlsUploadFile/" + xlsUpload.FileName.ToString()));
                string uploadedFile = (Server.MapPath("~/XlsUploadFile/" + xlsUpload.FileName.ToString()));
            }
            if (uplod)
            {
                string mess1 = "File has successfully uploaded";
                this.lblMessage.Text = mess1;
                Response.Redirect("ProductionIssueStatus.aspx");
            }
        }
        else
        {
            this.lblMessage.Text = "Please select file to upload.";
        }
    }
    public void MultiView(DataSet ds)
    {
     
    }  
    public bool UpdateData()
    {
        string backup = "";
        string pthForBackup = (Server.MapPath("~/Log/"));
        string filename = Convert.ToString(Session["CurrentFile"]);
        string SheetName = Convert.ToString(Request.QueryString["SheetName"]);
        string ID = txtSNo.Value;
        string ColumnName = ddlColumn.SelectedValue;
        string NewValue = txtNewValue.Value;
        DataTable dtBackup = new DataTable();
        if (filename.Length > 0 && SheetName.Length > 0)
        {
            string pth = (Server.MapPath("~/XlsUploadFile/" + filename));
            OleDbConnection excelCon = getConnection(pth);
            try
            {
                string strselect = " select " + ColumnName + " from [" + SheetName + "] where ID = " + ID + "";
                string str1 = "update [" + SheetName + "] set " + ColumnName + "='" + NewValue + "' where ID = " + ID + " ";
                OleDbCommand cmd;

                cmd= new OleDbCommand(str1, excelCon);
                excelCon.Open();

                using (OleDbDataAdapter adap = new OleDbDataAdapter(strselect, excelCon))
                {
                    adap.Fill(dtBackup);
                }
                if (dtBackup != null && dtBackup.Rows.Count > 0)
                {
                    string OldValue = Convert.ToString(dtBackup.Rows[0][ColumnName]);
                    backup = str1 + " <Old Value : " + OldValue + ">";
                }
                int rowsupdated = cmd.ExecuteNonQuery();
                if (rowsupdated > 0)
                {
                    backup = backup + "<Status : Success>";
                    backup = backup + "<updated by : " + clsIssueStatus.IPAddress() + ">";
                    clsIssueStatus.QueryLog(backup, pthForBackup);
                    return true;
                }
                else
                {
                    backup = str1;
                    backup = backup + "<Status : Unsuccess>";
                    backup = backup + "<Updated by : " + clsIssueStatus.IPAddress() + ">";
                    clsIssueStatus.QueryLog(backup, pthForBackup);
                    return false;
                }

            }
            catch (Exception ex)
            {
                return false;
            }
        }
        else
        {
            return false;
        }
    }
    protected void btnUpdate_Click(object sender, EventArgs e)
    {
     
    }
    public OleDbConnection getConnection(string PathOfXMLFileWithFileName)
    {
        string pth = PathOfXMLFileWithFileName;
        string strcon = string.Empty;
        if (Path.GetExtension(pth).ToLower().Equals(".xls") ||
            Path.GetExtension(pth).ToLower().Equals(".xlsx"))
        {
            strcon = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + pth + ";Extended Properties=\"Excel 12.0;HDR=YES;\"";
            //strcon = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + pth + ";Extended Properties=\"Excel 8.0;HDR=YES;\"";
        }
        else
        {
            strcon = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + pth + ";Extended Properties=\"Excel 12.0;HDR=YES;\"";
        }
        DataSet dtSheets = new DataSet();
        OleDbConnection excelCon = new OleDbConnection(strcon);
        return excelCon;
    }
}


.Aspx Page


<%@ Page Language="C#" AutoEventWireup="true" CodeFile="ProductionIssueStatus.aspx.cs"
    Inherits="ProductionIssueStatus" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title>Untitled Page</title>
    <link href="css/style.css" rel="stylesheet" type="text/css" />
    <style type="text/css">
table, tr, td, th{margin:0px; padding:0px;}
table.imagetable {
font-family: verdana,arial,sans-serif;
font-size:11px;
color:#333333;
border-width: 1px;
border-color: #999999;
border-collapse: collapse;
}
table.imagetable th {
background:#b5cfd2 url('cell-blue.jpg');
border-width: 1px;
padding: 8px;
border-style: solid;
border-color: #999999;
}
table.imagetable td {
background:#dcddc0 url('cell-grey.jpg');
border-width: 1px;
padding: 8px;
border-style: solid;
border-color: #999999;
}
table.sortable thead {
    background-color:#eee;
    color:#666666;
    font-weight: bold;
    cursor: pointer;
}

</style>

    <script type="text/javascript" language="javascript">
    function Filter(columnNo,valToFilter)
{
//var table=document.getElementById("Table1");
var table = document.all("Table1");
fltr1=valToFilter.value;
for (var r = 1; r < table.rows.length; r++) {
            table.rows[r].style.display = '';
        }
        for (var r = 1; r < table.rows.length; r++) {    
        ele1  = table.rows[r].cells[Number(columnNo)+1];
        ele1 = String(ele1.innerText);
        if (fltr1.length > 0) {    
     
        if (ele1.toLowerCase().indexOf(fltr1) >= 0 && table.rows[r].style.display == '') {
                        table.rows[r].style.display = '';
                    }
                    else if (table.rows[r].style.display == '') {
                        table.rows[r].style.display = 'none';
                    }
     
        }
     
        }

}

    </script>

    <script type="text/javascript" src="sorttable.js"></script>

</head>
<body>
    <form id="form1" runat="server">
        <div class="logo">
            <img src="images/logo.png" alt="Travel Boutique online" title="Travel Boutique online"></div>
        <div style="position: relative;">
            <div>
                <table>
                    <tr>
                        <td>
                            <asp:Label ID="label1" runat="server" Text="Choose File" Font-Bold="true"></asp:Label>
                            <asp:FileUpload ID="xlsUpload" runat="server" Font-Size="Small" />
                        </td>
                        <td>
                            <asp:Button ID="btnUpload" runat="server" Text="Upload" OnClick="btnUpload_Click" />
                        </td>
                        <td>
                            <asp:Label ID="lblMessage" runat="server" Text="" ForeColor="Red"></asp:Label>
                        </td>
                    </tr>
                </table>
            </div>
            <div style="margin: 5px">
                <div>
                    <span>
                        <br />
                        <span><b>List of files</b> :<br />
                            <br />
                        </span></span>
                </div>
                <table class="imagetable">
                    <tr>
                        <th>
                            Serial No.</th>
                        <th>
                            File Name</th>
                        <th>
                            Download</th>
                    </tr>
                    <%int i = 0; %>
                    <%foreach (System.IO.FileInfo fi in rgFiles)
                      {%>
                    <tr>
                        <td>
                            <%=++i%>
                        </td>
                        <td>
                            <a href="ProductionIssueStatus.aspx?fileName=<%=fi.Name %>">
                                <%=fi.Name%>
                            </a>
                        </td>
                        <td>
                            <%string Filepath = "XlsUploadFile/" + fi.Name;%>
                            <a href="<%=Filepath%>">Download</a>
                        </td>
                    </tr>
                    <%} %>
                </table>
            </div>
            <div>
                <br />
                <asp:Label ID="lblSelectedFile" runat="server"></asp:Label>
                <br />
                <br />
            </div>
            <div>
                <input type="button" onclick="ShowBlock()" style="float: right; margin-right: 10px;"
                    value="Update Data" />
            </div>
            <div id="updateBlock" style="position: absolute; left: 900px; right:100px; top: 10px; display: none;
                background-color: #FFF; border: 1px dashed #000;">
                <div class="form">
                    <div style="float: right; margin-right: 5px; cursor: pointer;" onclick="HideBlock()">
                        [ X ]</div>
                    <div style="margin: 10px 0px 10px 0px;">
                    </div>
                    <div style="margin-left: 5px">
                        <span>
                            <label>
                                ID :</label>
                            <input type="text" onkeypress="validate(event)" id="txtSNo" runat="server" />
                        </span><span>
                            <label>
                                Select Column :</label>
                            <asp:DropDownList ID="ddlColumn" runat="server">
                            </asp:DropDownList>
                        </span><span>
                            <label>
                                New Value :</label>
                            <input type="text" id="txtNewValue" runat="server" />
                        </span><span>
                            <label>
                            </label>
                            <asp:Button Height="23px" ID="btnUpdate" OnClientClick="return CheckData()" runat="server" Text="Update"
                                OnClick="btnUpdate_Click" />
                        </span>
                    </div>
                </div>
            </div>
            <div>
                <table class="imagetable">
                    <tr>
                        <%if (dsSheets != null)
                          { %>
                        <%foreach (System.Data.DataTable dt in dsSheets.Tables)
                          { %>
                        <th>
                            <a href="ProductionIssueStatus.aspx?SheetName=<%=dt.TableName %>" title="Click here to open sheet">
                                <%=dt.TableName.Remove(dt.TableName.IndexOf("$"))%>
                            </a>
                        </th>
                        <%} %>
                        <%} %>
                    </tr>
                </table>
            </div>
            <div style="width: 100%; margin: 20px 5px 0px 5px;">
                <%if (dtSheeet != null)
                  {%>
                <table class="sortable imagetable" id="Table1">
                    <%int SNo = 0; %>
                    <tr>
                        <th title="Click here to sort">
                            SNo.</th>
                        <% for (int j = 0; j < dtSheeet.Columns.Count; j++)
                           {%>
                        <th title="Click here to sort">
                            <%=dtSheeet.Columns[j].ColumnName%>
                            <!-- <br />
                        <input type="text" title="Write to filter" style="width: 100%;" onkeyup="Filter('<%=j %>',this);" /> -->
                        </th>
                        <%} %>
                    </tr>
                    <%foreach (System.Data.DataRow dr in dtSheeet.Rows)
                      {%>
                    <tr id="<%=SNo %>">
                        <td>
                            <%=++SNo %>
                        </td>
                        <% for (int j = 0; j < dtSheeet.Columns.Count; j++)
                           {%>
                        <td>
                            <%if (dr[j].ToString().Length > 200)
                              { %>
                            <%dr[j] = dr[j].ToString().Substring(0, 200); %>
                            <%} %>
                            <%=dr[j].ToString()%>
                        </td>
                        <%} %>
                    </tr>
                    <%} %>
                </table>
                <%} %>
            </div>
            <!-- Old Code -->
            <div runat="server" id="tab">
            </div>
        </div>
    </form>

    <script language="javascript" type="text/javascript">
    function CheckData()
    {
    debugger;
    var ddlcontrol=document.getElementById('<%=ddlColumn.ClientID %>');
    var ColumnName=ddlcontrol.options[ddlcontrol.selectedIndex].value;
    var sno= document.getElementById('<%=txtSNo.ClientID %>').value;
    var NewValue= document.getElementById('<%=txtNewValue.ClientID %>').value;
    if(sno.length>0)
    {}
    else
    {
    alert("Enter ID.");
    return false;
    }
 
    if(ColumnName=='Select')
    {
    alert("Select Column");
    return false;
    }  
 
     if(NewValue.length>0)
    {}  
    else
    {
    alert("Enter New value");
    return false;
    }
    return true;
    }
       
    function HideBlock()
    {
    document.getElementById("updateBlock").style.display='none';  
    }
    function ShowBlock()
    {
    document.getElementById("updateBlock").style.display='block';  
    }
    function validate(evt) {
if(evt.keyCode==8 || evt.keyCode==9)
{}
else
{
        var theEvent = evt || window.event;
        var key = theEvent.keyCode || theEvent.which;
        key = String.fromCharCode( key );
        var regex = /[0-9]|\./;
        if( !regex.test(key) ) {
        theEvent.returnValue = false;
        if(theEvent.preventDefault)
        theEvent.preventDefault();
        }
         }
       }    
    </script>

</body>
</html>