Error "External table is not in the expected format" - asp.net

here is my code
protected void btnSubmit_OnClick(object sender, EventArgs e)
{
string path = #"C:\Users\Mazen\Desktop\Source\Book1.xlsx";
String strExcelConn = "Provider=Microsoft.Jet.OLEDB.4.0;"
+ "Data Source=" + path + "; "
+ "Extended Properties='Excel 8.0;HDR=Yes'";
OleDbConnection connExcel = new OleDbConnection(strExcelConn);
OleDbCommand cmdExcel = new OleDbCommand();
cmdExcel.Connection = connExcel;
connExcel.Open();
System.Data.DataTable dtExcelSchema;
dtExcelSchema = connExcel.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null);
connExcel.Close();
DataSet ds = new DataSet();
string SheetName = dtExcelSchema.Rows[0]["TABLE_NAME"].ToString();
cmdExcel.CommandText = "SELECT ID, Name From [" + SheetName + "]";
OleDbDataAdapter da = new System.Data.OleDb.OleDbDataAdapter();
da.SelectCommand = cmdExcel;
da.Fill(ds);
}
its give an error how to fix it.. If i changed Jet to ACE so its gives an error
provider is not registered on the local machine. please help me

Try the following for your strExcelConn:
String strExcelConn = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + path + ";Extended Properties=Excel 12.0;";

Related

i want code for Autocomplete Textbox Using Database Return Value in c#.net

private void txtBoxSearch_TextChanged(object sender, EventArgs e)
{
AutoCompleteStringCollection namecollection = new AutoCompleteStringCollection();
SqlConnection con = new SqlConnection("connectionn string");
SqlCommand cmd = new SqlCommand();
cmd.Connection = con;
cmd.CommandType = CommandType.Text;
string searchFor = "%" + txtBoxSearch.Text + "%";
com.CommandText = "select cust_nm from Customer_Info where (cust_nm LIKE ' % " + searchFor + " %') ";
con.Open();
cmd.Parameters.AddWithValue("#name", searchFor);
SqlDataReader rea = cmd.ExecuteReader();
if (rea.HasRows == true)
{
while (rea.Read())
namecollection.Add(rea["name"].ToString());
}
rea.Close();
txtBoxSearch.AutoCompleteMode = AutoCompleteMode.Suggest;
txtBoxSearch.AutoCompleteSource = AutoCompleteSource.CustomSource;
txtBoxSearch.AutoCompleteCustomSource = namecollection;
}
i want textbox which is act as a search option
A few problems here
You set the CommandText on com but execute cmd
You set % both on the variable and on the CommandText
You add a parameter but you don't have the parameter in the CommandText

The Microsoft Jet database engine cannot open the file

I am writing a code to query .CSV file using SQL below is my code which works perfectly fine
string fileDirectory = #"C:\TechnicalTest\GskTest\Csv\SampleData.csv";
string strCSVConnString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source="
+ fileDirectory + ";Extended Properties='text;HDR=YES;'";
string sqlCust = "Select Count(order_id), order_id, contact_id from SampleData.csv "
+ "Group by order_id, contact_id "
+ "Order by 1 Desc";
string sqlProd = "Select Count(order_id), product_id from SampleData.csv "
+ "Group by product_id "
+ "Order by 1 Desc";
string sqlOrders = "Select Count(order_id) from SampleData.csv "
+"Order by 1 Desc";
OleDbConnection con = new OleDbConnection("Provider=Microsoft.Jet.OleDb.4.0; Data Source = " + System.IO.Path.GetDirectoryName(fileDirectory) + "; Extended Properties = \"Text;HDR=YES;FMT=Delimited\"");
con.Open();
OleDbDataAdapter daCust = new OleDbDataAdapter(sqlCust, con);
DataTable dtCust = new DataTable();
daCust.Fill(dtCust);
OleDbDataAdapter daProd = new OleDbDataAdapter(sqlProd, con);
DataTable dtProd = new DataTable();
daProd.Fill(dtProd);
OleDbDataAdapter daOrders = new OleDbDataAdapter(sqlOrders, con);
DataTable dtOrders = new DataTable();
daOrders.Fill(dtOrders);
con.Close();
But when I am trying to call the same code from the function by passing the file path which is retrieved from asp.net file upload control it does not work. Please see the code below.
protected void btnSubmit_Click(object sender, EventArgs e)
{
if (fupPath.HasFile)
{
string filename = Path.GetFileName(fupPath.FileName);
String csv_file_path = Path.Combine(Server.MapPath("~/Csv"), filename);
fupPath.SaveAs(csv_file_path);
Summery(csv_file_path);
DataTable csvData = GetDataTabletFromCSVFile(csv_file_path);
Response.Write("Rows count:" + csvData.Rows.Count);
//dtSummary(csvData);
}
}
protected void Summery(string fileName)
{
//string fileDirectory = #"C:\TechnicalTest\GskTest\Csv\SampleData.csv";
string fileDirectory = fileName;
//string strCSVConnString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source="
// + System.IO.Path.GetDirectoryName(fileDirectory) + ";Extended Properties='text;HDR=YES;FMT=Delimited\'";
string sqlCust = "Select Count(order_id), order_id, contact_id from SampleData.csv "
+ "Group by order_id, contact_id "
+ "Order by 1 Desc";
string sqlProd = "Select Count(order_id), product_id from SampleData.csv "
+ "Group by product_id "
+ "Order by 1 Desc";
string sqlOrders = "Select Count(order_id) from SampleData.csv "
+ "Order by 1 Desc";
OleDbConnection conn = new OleDbConnection("Provider=Microsoft.Jet.OleDb.4.0; Data Source = " + System.IO.Path.GetDirectoryName(fileDirectory) + "; Extended Properties = \"Text;HDR=YES;FMT=Delimited\"");
//OleDbConnection conn = new OleDbConnection(strCSVConnString);
conn.Open();
OleDbDataAdapter daCust = new OleDbDataAdapter(sqlCust, conn);
DataTable dtCust = new DataTable();
daCust.Fill(dtCust);
daCust.Dispose();
OleDbDataAdapter daProd = new OleDbDataAdapter(sqlProd, conn);
DataTable dtProd = new DataTable();
daProd.Fill(dtProd);
daProd.Dispose();
OleDbDataAdapter daOrders = new OleDbDataAdapter(sqlOrders, conn);
DataTable dtOrders = new DataTable();
daOrders.Fill(dtOrders);
daOrders.Dispose();
conn.Close();
}
You need to call a sheet name SheetName$ instead of file name SampleData.csv.
For example,
Select Count(order_id), order_id, contact_id from [SheetName$]
Normally, here is how you get a file path in ASP.Net, because you do not know the drive letter where your web application is hosted. In addition, you do not have access to a file located outside of web application.
var filePath = string.Format("{0}App_Data\\ExportImport\\{1}",
HttpRuntime.AppDomainAppPath, "SampleData.csv");

There is no row at position 0 error at asp.net

I was writing a web based program and this is my authentication page. It was working fine but suddenly it started to give that error.
Here is my code:
else if (LoginAs.SelectedValue == "Student")
{
string tableName = "StudentTable";
String name = "", surname = "", email = "";
string query = "Select level from " + tableName + " where ID='" + idBox.Text + "'";
SqlCommand cmd = new SqlCommand(query, con);
string level = Convert.ToString(cmd.ExecuteScalar());
CreateUser(con, tableName, ref name, ref surname, ref email);
query = "Select program from " + tableName + " where ID='" + idBox.Text + "'";
cmd = new SqlCommand(query, con);
string program = Convert.ToString(cmd.ExecuteScalar());
MyGlobals.student = new Student(Convert.ToInt32(idBox.Text), "Active", email, name, surname, password, level, program);
MyGlobals.currentID = idBox.Text;
query = "Select * from RegisterTable where StudentID='" + idBox.Text + "'";
cmd = new SqlCommand(query, con);
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataTable dt = new DataTable();
da.Fill(dt);
foreach (DataRow dr in dt.Rows)
{
query = "SELECT * FROM CourseTable WHERE CourseCode='" + dr["CourseCode"] + "' AND CourseNumber='" + dr["CourseNumber"] + "' AND Term='" + dr["Term"] + "'";
cmd = new SqlCommand(query, con);
SqlDataAdapter da2 = new SqlDataAdapter(cmd);
DataTable dt2 = new DataTable();
da2.Fill(dt2);
DataRow dr2 = dt2.Rows[0]; //ERROR COMES AT HERE
Course course = new Course(dr2["InstructorName"].ToString(), dr2["CourseCode"].ToString(), dr2["CourseNumber"].ToString(), dr2["CourseName"].ToString(), dr2["Term"].ToString(), dr2["CRN"].ToString(), dr2["Level"].ToString(), dr2["Credit"].ToString(), dr2["Description"].ToString(), dr2["Capacity"].ToString());
Register reg = new Register(course, MyGlobals.student);
MyGlobals.student.addToSchedule(reg);
}
int num = (int)Application["OnlineUsers"];
Response.Redirect("Student.aspx");
}
Can anyone help me with this? Thanks in advance.
You don't specify where the exception is thrown but a very common reason for this (my opinion) is that your query doesn't return any results (or rows).

SQL ASP.NET INSERT troubles (part 2)

And i am back again.
I have asked a similair question before, but even with the help of the previous anwser and trying it with questionmarks or instead of Add i've tried AddWithValue i didn't have any luck.
I tried to change the txt_Naam to txt_Naam.Text, nothing.
Also putting [] around the columnnames, no luck.
It keeps giving me this "Syntax error in INSERT INTO statement.".
This time i got nowhere with the code below.
Probably something small, but i can't figure it out. (Again...)
protected void btn_final_Click(object sender, EventArgs e)
{
string fact_adres = txt_Naam.Text + "," + txt_Anaam.Text + "," + txt_Adres.Text + "," + txt_Toevoeg.Text + "," + txt_Pcode.Text + "," + txt_Plaats.Text + "," + txt_Email.Text ;
string fact_adres1 = txt_Naam1.Text + "," + txt_Anaam1.Text + "," + txt_Adres1.Text + "," + txt_Toevoeg1.Text + "," + txt_Pcode1.Text + "," + txt_Plaats1.Text + "," + txt_Email1.Text;
string a = "1";
OleDbConnection conn = new OleDbConnection();
conn.ConnectionString = "Provider=Microsoft.ACE.OLEDB.12.0; "
+ "Data Source=|DataDirectory|webwinkel.accdb";
OleDbCommand cmd = new OleDbCommand();
cmd.Connection = conn;
cmd.CommandText = "INSERT INTO Order (factuur_adres_id, verzend_adres_id, totaalprijs) VALUES (?, ?, ?);";
cmd.Parameters.Add("#factuur_adres", OleDbType.VarChar, 125).Value = fact_adres;
cmd.Parameters.Add("#verzend_adres", OleDbType.VarChar, 125).Value = fact_adres1;
cmd.Parameters.Add("#totaal_prijs", OleDbType.VarChar, 7).Value = a;
try
{
conn.Open();
OleDbDataReader reader = cmd.ExecuteReader();
reader.Close();
}
catch (Exception exc)
{
Label1.Text = exc.Message;
}
finally
{
conn.Close();
Session["Winkelwagen"] = null;
}
}
You command text should be
cmd.CommandText = "INSERT INTO Order (factuur_adres_id, verzend_adres_id, totaalprijs) VALUES (#factuur_adres,#verzend_adres, #totaal_prijs)";
Updated answer:
run your code with setting parameters, directly pass the value and check that it works or not
cmd.CommandText = "INSERT INTO Order (factuur_adres_id, verzend_adres_id, totaalprijs) VALUES ('abc','def','adf')";
When you are inserting don't you have to use
cmd.ExecuteNonQuery()
Instead of cmd.ExecuteReader() ??

Strange! MySQL update not working without error

The below is my code to create account in my project. The code is working perfect till Response.Write(iduser) but the UPDATE command is not working. No error found using exception but MySQL's record is not updated.
try
{
string pet1 = "admin#testlite.php";
string MyConString = "DRIVER={MySQL ODBC 3.51 Driver};" + "SERVER=localhost;" + "DATABASE=newtest;" + "UID=root;" + "PASSWORD=**********;" + "OPTION=3";
OdbcConnection MyConnection = new OdbcConnection(MyConString);
OdbcCommand cmd = new OdbcCommand("Select id_user from awm_accounts where email=?", MyConnection);
cmd.Parameters.Add("#val1", OdbcType.VarChar, 255).Value = pet1;
MyConnection.Open();
OdbcDataReader dr = cmd.ExecuteReader();
if (dr.HasRows == false)
{
throw new Exception();
}
if (dr.Read())
{
int iduser = Convert.ToInt32(dr[0].ToString());
Account acct = new Account();
acct.Email = username.Text + domain.Text;
acct.MailIncomingLogin = username.Text + domain.Text;
acct.MailIncomingHost = "imap." + DropDownList1.SelectedValue;
acct.MailIncomingPassword = password.Text;
acct.MailIncomingPort = 993;
acct.MailOutgoingHost = "smtp." + DropDownList1.SelectedValue;
acct.MailOutgoingPort = 465;
acct.MailIncomingProtocol = IncomingMailProtocol.Imap4;
acct.MailOutgoingAuthentication = true;
acct.DefaultAccount = false;
acct.IDUser = 1;
integr.CreateUserFromAccount(acct);
Response.Write(iduser);
if (!IsPostBack)
{
cmd = new OdbcCommand("UPDATE awm_accounts SET id_user=? WHERE email=? ", MyConnection);
cmd.Parameters.Add("#tb_nickname", OdbcType.Int, 11).Value = iduser;
cmd.Parameters.Add("#tb_fullname", OdbcType.VarChar, 255).Value = username.Text + domain.Text;
cmd.ExecuteNonQuery();
}
}
MyConnection.Close();
}
catch (Exception exp)
{
Response.Write(exp);
}
I'm not sure about the Response.Write part but I am sure that you create a SQLCommand but never actually execute it.
Did you forget to put a cmd.executeNonScalar() in there?

Resources