I am new to the C# platform. I have made the application for importing Excel data in which I have showed the two text fields. The first takes path of Excel file, the second takes sheet name, and when I pressed the load button then it imports the data from Excel.
But there is a problem when I entered the invalid sheet name then application crashed and because of the system.Data.OleDb.OleDbException
. The only thing I want to display the message `please enter the correct sheet number' on entering invalid sheet name.
Here is the code:
string PathConn = "Provider =Microsoft.Jet.OLEDB.4.0;Data Source=" + opentextfeild.Text + ";Extended Properties=\"Excel 8.0;HDR=Yes;\";";
OleDbConnection conn = new OleDbConnection(PathConn);
OleDbDataAdapter myDataAdapter = new OleDbDataAdapter("Select email from [" + loadtextfeild.Text + "$] where email like '%@%' ", conn);
DataTable dt = new DataTable();
myDataAdapter.Fill(dt);
displayviewgrid.DataSource = dt;
When I entered the invalid sheet name then it creates the exception on the line myDataAdapter.Fill(dt);
.
Add a try/catch block - Example