Try this code:
<table><tbody><tr><td><asp:fileupload id="testFileUpload" runat="server" xmlns:asp="#unknown" /></td><td><asp:button id="btnUpload" runat="server" height="21px" text="Upload" width="92px" onclick="btnUpload_Click" xmlns:asp="#unknown" /></td></tr></tbody></table>
<br />
<asp:gridview id="dataGridView" runat="server" xmlns:asp="#unknown">
</asp:gridview>
In your button event:
try
{
if (testFileUpload.HasFile)
{
fileName = Path.GetFileName(testFileUpload.PostedFile.FileName);
fileExtension = Path.GetExtension(testFileUpload.PostedFile.FileName);
fileLocation = Server.MapPath("~/App_Data/" + fileName);
GetData(fileLocation);
Label1.Text = "File is ok to upload.";
}
}
catch (Exception ex)
{
Label1.Text = "File is not expected formated.";
}
public void GetData(string loc)
{
testFileUpload.SaveAs(fileLocation);
if (fileExtension == ".xls")
{
connectionString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + loc + ";Extended Properties=\"Excel 8.0;HDR=Yes;IMEX=2\"";
}
else if (fileExtension == ".xlsx")
{
connectionString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + loc + ";Extended Properties=\"Excel 12.0;HDR=Yes;IMEX=2\"";
}
dtExcelRecords.Clear();
dtExcelRecords.Reset();
con = new OleDbConnection(connectionString);
cmd.CommandType = System.Data.CommandType.Text;
cmd.Connection = con;
dAdapter = new OleDbDataAdapter(cmd);
con.Open();
dtExcelSheetName = con.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null);
getExcelSheetName = dtExcelSheetName.Rows[0]["Table_Name"].ToString();
cmd.CommandText = "SELECT * FROM [" + getExcelSheetName + "]";
dAdapter.SelectCommand = cmd;
dAdapter.Fill(dtExcelRecords);
con.Close();
dataGridView.DataSource = dtExcelRecords;
dataGridView.DataBind();
}