I've been doing a C# project where I browse and view an Excel File into a gridview. However, there is an error message which I don't understand. Can someone please help me out on this.
This is the code I used:
private void buttonUpload_Click(object sender, EventArgs e)
{
string connectionString = String.Format(#"Data Source={0};Extended Properties=""Excel 8.0;HDR=YES;IMEX=1;""", textBoxFileName.Text);
string query = String.Format("select * from [{0}$]", "Sheet1");
SqlDataAdapter dataAdapter = new SqlDataAdapter(query, connectionString);
DataSet dataSet = new DataSet();
dataAdapter.Fill(dataSet);
dataGridView1.DataSource = dataSet.Tables[0];
}
This is the error message:
"A network-related or instance-specific error occurred while establishing
a connection to SQL Server. The server was not found or was not accessible.
Verify that the instance name is correct and that SQL Server is configured
to allow remote connections.
(provider: SQL Network Interfaces,
error: 26 - Error Locating Server/Instance Specified)."
You are trying to connect to Excel via a SqlConnection.
To connect to Excel use OleDBConnection:
private void buttonUpload_Click(object sender, EventArgs e)
{
string connectionString = String.Format(#"Data Source={0};Extended Properties=""Excel 8.0;HDR=YES;IMEX=1;""", textBoxFileName.Text)
var objConn = new OleDbConnection(connectionString);
objConn.Open();
OleDbCommand objCmdSelect = new OleDbCommand("SELECT * FROM [Sheet1$]", objConn);
OleDbDataAdapter objAdapter1 = new OleDbDataAdapter();
objAdapter1.SelectCommand = objCmdSelect;
DataSet objDataset1 = new DataSet();
objAdapter1.Fill(objDataset1);
objConn.Close();
}
You can not use SqlConnection or SqlDataAdapter for ODBC or JET connections. Use OleDbConnection or OleDbDataAdapter.
Please also make sure to dispose of connections and resources in a timely manner. Using the using statement is recommended here.
private void buttonUpload_Click(object sender, EventArgs e)
{
string connectionString = String.Format(#"Data Source={0};Extended Properties=""Excel 8.0;HDR=YES;IMEX=1;""", textBoxFileName.Text);
DataSet objDataset1 = new DataSet();
using (OleDbConnection objConn = new OleDbConnection(connectionString))
{
objConn.Open();
using (OleDbCommand objCmdSelect = new OleDbCommand("SELECT * FROM [Sheet1$]", objConn))
using (OleDbDataAdapter objAdapter1 = new OleDbDataAdapter())
{
objAdapter1.SelectCommand = objCmdSelect;
objAdapter1.Fill(objDataset1);
}
}
}
Related
I have an error while connecting my project into mysql database so i have added the code bellow to my button to fetch all rows and display it in a gridView
protected void Button1_Click(object sender, EventArgs e)
{
MySqlConnection myconn = new MySqlConnection("server=localhost;uid=root;password=;database=y;");
string strSQL = "select * from welcome";
myconn.Open();
MySqlDataAdapter mydata = new MySqlDataAdapter(strSQL, myconn);
MySqlCommandBuilder cBuilder = new MySqlCommandBuilder(mydata);
System.Data.DataSet ds = new System.Data.DataSet();
mydata.Fill(ds);
GridView1.DataSource = ds;
GridView1.DataBind();
myconn.Close();
}
When running the the app it shows an error in myconn.Open();
An exception of type 'MySql.Data.MySqlClient.MySqlException' occurred in MySql.Data.dll but was not handled in user code
Additional information: The host localhost does not support SSL connections.
and it pointed to myconn.Open();
change myconn to :
MySqlConnection myconn = new MySqlConnection("server=localhost;uid=root;password=;database=y;sslmode=none");
Make sure that you are adding sslmode=none in myconn
better try with Entity Frame work
Add ADO.NET Entity model,If will ask to connect db and give some name(ex :userentities)
Then, use below code in your coding
userentities context = new userentities();
protected void Button1_Click(object sender, EventArgs e)
{
using (var dbTransactionContext = context.Database.BeginTransaction())
{
//then do the operation
}
}
It's really easy
or other wise follow these steps
1. add your connection string in web config
<add name="UserContext" connectionString="server=localhost;User Id=root;password='';database=databasename;convert zero datetime=True" providerName="MySql.Data.MySqlClient" />
Add follow codes in your code
private MySqlConnection con;
con = new MySqlConnection();
con.ConnectionString = ConfigurationManager.ConnectionStrings["UserContext"].ConnectionString;
con.Open();
am getting the following error while trying to import data from excel to the database.
The Microsoft Office Access database engine could not find the object
'C:\Users\DAKTARI\Desktop\smarttable.xls'
this is my code behind that am using.
public partial class Smarttable : System.Web.UI.Page
{
OleDbConnection Econ;
SqlConnection con;
string constr, Query, sqlconn;
protected void Page_Load(object sender, EventArgs e)
{
}
private void ExcelConn(string FilePath)
{
constr = string.Format(#"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\Users\DAKTARI\Desktop\smarttable.xls;Extended Properties=""Excel 12.0 Xml;HDR=YES;""");
Econ = new OleDbConnection(constr);
}
private void connection()
{
sqlconn = ConfigurationManager.ConnectionStrings["SqlCom"].ConnectionString;
con = new SqlConnection(sqlconn);
}
private void InsertExcelRecords(string FilePath)
{
ExcelConn(FilePath);
Query = string.Format("Select [InvoiceNumber],[AmountPaid],[Remarks] FROM [C:\\Users\\DAKTARI\\Desktop\\smarttable.xls]", "Orders$");
OleDbCommand Ecom = new OleDbCommand(Query, Econ);
Econ.Open();
DataSet ds = new DataSet();
OleDbDataAdapter oda = new OleDbDataAdapter(Query, Econ);
Econ.Close();
oda.Fill(ds);
DataTable Exceldt = ds.Tables[0];
connection();
//creating object of SqlBulkCopy
SqlBulkCopy objbulk = new SqlBulkCopy(con);
//assigning Destination table name
objbulk.DestinationTableName = "smarttable";
//Mapping Table column
objbulk.ColumnMappings.Add("InvoiceNumber", "InvoiceNumber");
objbulk.ColumnMappings.Add("AmountPaid", "AmountPaid");
objbulk.ColumnMappings.Add("Remarks", "Remarks");
//inserting Datatable Records to DataBase
con.Open();
objbulk.WriteToServer(Exceldt);
con.Close();
}
protected void Button1_Click(object sender, EventArgs e)
{
string CurrentFilePath = Path.GetFullPath(FileUpload1.PostedFile.FileName);
InsertExcelRecords(CurrentFilePath);
}
}
Your Excel file format uses XLS which means for Office 2003 or earlier, but you're using ACE OLEDB provider which used for Office 2007 or later:
constr = string.Format(#"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\Users\DAKTARI\Desktop\smarttable.xls;Extended Properties=""Excel 12.0 Xml;HDR=YES;"");
The correct usage is using Jet 4.0 provider like this:
constr = string.Format(#"Provider=Microsoft.Jet.OLEDB.4.0;Data Source={0};Extended Properties='Excel 8.0;HDR=YES;'", FilePath);
Also you have second issue which a wrong query string is used to read the data inside worksheet:
Query = string.Format("Select [InvoiceNumber],[AmountPaid],[Remarks] FROM [C:\\Users\\DAKTARI\\Desktop\\smarttable.xls]", "Orders$");
This should be changed to proper form below:
Query = "SELECT [InvoiceNumber],[AmountPaid],[Remarks] FROM [Orders$]";
Change this line
Query = string.Format("Select [InvoiceNumber],[AmountPaid],[Remarks] FROM [C:\\Users\\DAKTARI\\Desktop\\smarttable.xls]", "Orders$");
To
Query = "Select [InvoiceNumber],[AmountPaid],[Remarks] FROM [Orders$]";
The FROM needs to be followed by the Sheet Name which is treated like a table
I´d like to know if there is anything wrong in this code because it doesn´t connect to the datasource. If i do it with an SQLDataSource in the aspx file there is no error. But why don´t the commands work within my code-behind .cs-file? I hope you understand my problem because i´m just new in .net-coding.
protected void Page_Load(object sender, EventArgs e)
{
//var conString = ConfigurationManager.ConnectionStrings["ConnectionString"];
//string strConnString = conString.ConnectionString;
string constr = ConfigurationManager.ConnectionStrings["OLEDB"].ConnectionString;
string query = "selectcommand";
SqlConnection conn = new SqlConnection("Data Source=source.com;Persist Security Info=True;Password=xxxxxxxxx;User ID=system");
SqlCommand cmd = new SqlCommand(query, conn);
DataSet ds = new DataSet();
SqlDataAdapter da = new SqlDataAdapter(cmd);
da.Fill(ds);
GridView1.DataSource = ds;
GridView1.DataBind();
conn.Close();
}
It says: "Network path not found"
Row 40: da.Fill(ds);
If i add a Provider into the SqlConnection it says: "Keyword not supported: Provider" <-- that´s why i deleted it out of the command.
I did some coding on connecting data using Azure database on Windows Form and when I tried to retrieve the data, I received the following error:
An unhandled exception of type 'System.Data.SqlClient.SqlException' occurred in System.Data.dll.
Also in addition, I received a Login failed for user ''. When I tried to retrieve the data and located at myConnection.Open();
private void btnRetrieve_Click(object sender, EventArgs e)
{
//Create a connection calling the App.config
string conn = ConfigurationManager.ConnectionStrings["NYPConnection"].ConnectionString;
//The query to use
string query = "SELECT * FROM Users";
SqlConnection myconnection = new SqlConnection(conn);
//Create a Data Adapter
SqlDataAdapter dadapter = new SqlDataAdapter(query, myconnection);
//Create the dataset
DataSet ds = new DataSet();
//Open the connection
******myconnection.Open();******
//Fill the Data Adapter
dadapter.Fill(ds, "Users");
myconnection.Close();
//Bind the datagridview with the data set
dataGridView1.DataSource = ds;
dataGridView1.DataMember = "Users";
}
Print out the value of conn, using the following code:
string conn = ConfigurationManager.ConnectionStrings["NYPConnection"].ConnectionString;
Debug.WriteLine("conn= " + conn);
Have a look in the output window and you will probably find that conn is set to an empty string or maybe does not have the user name specified.
I'm trying to import xlsx to datagrid using oledb.
but I'm getting this: Syntax error (missing operator) in query expression.I've read other related posts but didn't helped
this is the code:
private void button1_Click(object sender, EventArgs e)
{
OleDbConnection conn = new OleDbConnection();
conn.ConnectionString = #"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\alm1.xlsx" + #";Extended Properties=""Excel 12.0 Xml;HDR=YES;ImportMixedTypes=Text;TypeGuessRows=0""";
OleDbCommand command = new OleDbCommand("SELECT TXT" + "FROM [2$]", conn);
DataSet dstxt = new DataSet();
OleDbDataAdapter adapter = new OleDbDataAdapter(command);
adapter.Fill(dstxt);
dataGridView1.DataSource = dstxt.Tables[0];
can anyone help? I'm pretty sure it's a stupid mistake of me but can't figure it out.