import data from excel to sql using asp.net - c#

when i import data from excel to sql loops dont stop when columns became null, how i do this.
this is my code :-
protected void insertdata_Click(object sender, EventArgs e)
{
OleDbConnection oledbConn = new OleDbConnection(#"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + Server.MapPath("test4.xlsx") + ";Extended Properties=Excel 12.0;");
try
{
OleDbCommand ocmd = new OleDbCommand("select [Notifications],[ReqStart],[Type],[ReqTime],[OrderNum],[FuncLoc],[CustomerCode],[CustomerName],[Rg],[city],[Phone],[Street],[Distrit] from [Sheet1$]", oledbConn);
oledbConn.Open();
OleDbDataReader odr = ocmd.ExecuteReader();
string Notifications = "";
string ReqStart = " ";
string Type = " ";
string ReqTime = " ";
string OrderNum = " ";
string FuncLoc = " ";
string CustomerCode = " ";
string CustomerName = " ";
string Rg = " ";
string city = " ";
string Phone = " ";
string Street = " ";
string Distrit = " ";
while (odr.Read())
{
Notifications = valid(odr, 0);
ReqStart = valid(odr, 1);
Type = valid(odr, 2);
ReqTime = valid(odr, 3);
OrderNum = valid(odr, 4);
FuncLoc = valid(odr, 5);
CustomerCode = valid(odr, 6);
CustomerName = valid(odr, 7);
Rg = valid(odr, 8);
city = valid(odr, 9);
Phone = valid(odr, 10);
Street = valid(odr, 11);
Distrit = valid(odr, 12);
insertdataintosql(Notifications, ReqStart, Type, ReqTime, OrderNum, FuncLoc, CustomerCode, CustomerName, Rg, city, Phone, Street, Distrit);
}
oledbConn.Close();
}
catch(DataException ex)
{
lblmssg.Text = ex.Message;
lblmssg.ForeColor = System.Drawing.Color.Red;
}
finally
{
lblmssg.Text = "Data Inserted Sucessfully";
lblmssg.ForeColor = System.Drawing.Color.Green;
}
}
protected string valid(OleDbDataReader myreader, int stval)
{
object val = myreader[stval];
if (val != DBNull.Value)
{
return val.ToString();
}
else
{
return Convert.ToString(0);
}
}
public void insertdataintosql(string Notifications, string ReqStart, string Type, string ReqTime, string OrderNum, string FuncLoc, string CustomerCode, string CustomerName, string Rg, string city, string Phone, string Street, string Distrit)
{
SqlConnection sqlconn = new SqlConnection("Data Source=.;Initial Catalog=White_Whale;Integrated Security=True");
using (SqlCommand cmd=new SqlCommand())
{
cmd.Connection = sqlconn;
cmd.CommandText = "insert into Customers(customer_code,customer_name,RgCode,CityCode,Phone,Distriet,Street) values(#customer_code,#customer_name,#RgCode,#CityCode,#Phone,#Distriet,#Street)";
cmd.Parameters.Add("#customer_code", SqlDbType.VarChar, 20).Value = CustomerCode;
cmd.Parameters.Add("#customer_name", SqlDbType.VarChar, 100).Value = CustomerName;
cmd.Parameters.Add("#RgCode", SqlDbType.Int).Value = Convert.ToInt32(Rg);
cmd.Parameters.Add("#CityCode", SqlDbType.Int).Value = Convert.ToInt32(city);
cmd.Parameters.Add("#Phone", SqlDbType.VarChar, 12).Value = Phone;
cmd.Parameters.Add("#Distriet", SqlDbType.VarChar, 12).Value = Distrit;
cmd.Parameters.Add("#Street", SqlDbType.NVarChar, 100).Value = Street;
cmd.CommandType = CommandType.Text;
sqlconn.Open();
cmd.ExecuteNonQuery();
sqlconn.Close();
}
using (SqlCommand cmd = new SqlCommand())
{
cmd.Connection = sqlconn;
cmd.CommandText = "insert into Notification(notification,type_code,order_Num,funLoc_Code,customer_code) values (#notification,#type_code,#order_Num,#funLoc_Code,#customer_code)";
cmd.Parameters.Add("#notification", SqlDbType.VarChar,30).Value = Notifications;
//cmd.Parameters.Add("#req_start", SqlDbType.Date).Value = DateTime.ParseExact(ReqStart,"dd-MM-yyyy",null);
cmd.Parameters.Add("#type_code", SqlDbType.Int).Value = Convert.ToInt32(Type);
//cmd.Parameters.Add("#ReqTime", SqlDbType.Bit).Value = ReqTime;
cmd.Parameters.Add("#order_Num", SqlDbType.VarChar, 30).Value = OrderNum;
cmd.Parameters.Add("#funLoc_Code", SqlDbType.Int).Value = Convert.ToInt32(OrderNum);
cmd.Parameters.Add("#customer_code", SqlDbType.VarChar, 20).Value = CustomerCode;
cmd.CommandType = CommandType.Text;
sqlconn.Open();
cmd.ExecuteNonQuery();
sqlconn.Close();
}
}
}

One thing you could do is create an array of objects equal to the number of columns in your spreadsheet and then check if all of those values are DBNull using LINQ
object[] dataTest = new object[colCount];
If (dataTest.All(x => x == DBNull.Value))
break;

Related

How to call a function in a command?

I want to use the function "MyPlaces". What should I use instead of commandType.StoredProcedure
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
string connStr = ConfigurationManager.ConnectionStrings["MyDbConn"].ToString();
SqlConnection conn = new SqlConnection(connStr);
SqlCommand cmd = new SqlCommand("MyPlaces", conn);
cmd.CommandType = CommandType.StoredProcedure; //This part gives me an error
string email = Session["oldemailuser"].ToString();
cmd.Parameters.Add(new SqlParameter("#email", email));
conn.Open();
SqlDataReader rdr = cmd.ExecuteReader(CommandBehavior.CloseConnection);
string s = "<br />";
while (rdr.Read())
{
string name = s + " " + rdr.GetString(rdr.GetOrdinal("name"))
+ " located in ";
string location = rdr.GetString(rdr.GetOrdinal("location"))
+ " &nbsp";
Label lbl_name = new Label();
lbl_name.Text = email;
form1.Controls.Add(lbl_name);
Label lbl_location = new Label();
lbl_location.Text = email;
form1.Controls.Add(lbl_location);
}
}
Hope your sql function name is "Myplaces".If So,Then Modify your code with this :
string email = Session["oldemailuser"].ToString();
SqlConnection conn = new SqlConnection(connStr);
SqlCommand cmd = new SqlCommand(conn);
cmd.CommandText = "SELECT MyPlaces(#email)";
cmd.CommandType = CommandType.Text;
cmd.Parameters.Add(new SqlParameter("#email", email));
conn.Open();

Fetching next row from access database in VS C# 2010

I have tried the following code but it throws exception "No value given for one or more required parameters".
protected void Button2_Click(object sender, EventArgs e)
{
string constr = #"Provider=Microsoft.Jet.OLEDB.4.0; Data
Source=C:\Users\yogi\Documents\mydb.mdb";
string cmdstr1 = "select count(*) from quant_level1";
OleDbConnection con1 = new OleDbConnection(constr);
OleDbCommand com1 = new OleDbCommand(cmdstr1, con1);
con1.Open();
int count = (int) com1.ExecuteScalar();
int i = 2;
while (i <= count)
{
string cmdstr = "select * from quant_level1 where id = i";
OleDbConnection con = new OleDbConnection(constr);
OleDbCommand com = new OleDbCommand(cmdstr, con);
con.Open();
OleDbDataReader reader = com.ExecuteReader();
reader.Read();
label1.Text = String.Format("{0}", reader[1]);
RadioButton1.Text = String.Format("{0}", reader[2]);
RadioButton2.Text = String.Format("{0}", reader[3]);
RadioButton3.Text = String.Format("{0}", reader[4]);
RadioButton4.Text = String.Format("{0}", reader[5]);
con.Close();
i++;
}
con1.Close();
}
One mistake is within the select Statement:
You are trying to select an ID which you don't provide.
string cmdstr = "select * from quant_level1 where id = i";
Your select statement should look like:
string cmdstr = "select * from quant_level1 where id = " + i;
Your Loop-counter is/was within your string. It won't be replaced automatically.
try this -
work only if you are using Web Application
protected void Button2_Click(object sender, EventArgs e)
{
int i;
if (ViewState["count"] != null)
i = Convert.ToInt32(ViewState["count"].ToString());
else
i = 2; // assuming that it is your starting point as given in question
string constr = #"Provider=Microsoft.Jet.OLEDB.4.0; Data Source=C:\Users\yogi\Documents\mydb.mdb";
string cmdstr1 = "select count(*) from quant_level1";
OleDbConnection con1 = new OleDbConnection(constr);
OleDbCommand com1 = new OleDbCommand(cmdstr1, con1);
con1.Open();
int count = (int)com1.ExecuteScalar();
if (i < count)
{
string cmdstr = "select * from quant_level1 where id = i";
OleDbConnection con = new OleDbConnection(constr);
OleDbCommand com = new OleDbCommand(cmdstr, con);
con.Open();
OleDbDataReader reader = com.ExecuteReader();
reader.Read();
label1.Text = String.Format("{0}", reader[1]);
RadioButton1.Text = String.Format("{0}", reader[2]);
RadioButton2.Text = String.Format("{0}", reader[3]);
RadioButton3.Text = String.Format("{0}", reader[4]);
RadioButton4.Text = String.Format("{0}", reader[5]);
con.Close();
i++;
ViewState["count"] = i.ToString();
}
con1.Close();
}
This will do the trick in your case. happy coding :)
Since you want to fetch next row every time on clicking the button.
int i=2;
protected void Button2_Click(object sender, EventArgs e)
{
string constr = #"Provider=Microsoft.Jet.OLEDB.4.0; Data
Source=C:\Users\yogi\Documents\mydb.mdb";
string cmdstr1 = "select * from quant_level1 where id ="+i;
OleDbConnection con1 = new OleDbConnection(constr);
OleDbCommand com1 = new OleDbCommand(cmdstr1, con1);
con1.Open();
if(reader.Read())
{
label1.Text = String.Format("{0}", reader[1]);
RadioButton1.Text = String.Format("{0}", reader[2]);
RadioButton2.Text = String.Format("{0}", reader[3]);
RadioButton3.Text = String.Format("{0}", reader[4]);
RadioButton4.Text = String.Format("{0}", reader[5]);
i++;
}
con1.Close();
}

DataRoutines not creating data in Access Database

today, I am trying to use DataRoutines to insert some values into my Access Database. However, it did not work as well as there were no records created. Does anyone know what's wrong with my code?
This is my DataRoutines (dataroutines2) file
public void CreateRecs(string strUserId)
{
OleDbConnection mDB = new OleDbConnection();
mDB.ConnectionString = "Provider = Microsoft.ACE.OLEDB.12.0;Data source="
+ Server.MapPath("~/App_Data/webBase.accdb");
OleDbCommand cmd; OleDbDataReader rdr;
string strSql;
string strOFlag = "F";
// check to see if there is an active order record
strSql = "SELECT eStatus FROM enrolInfo WHERE eUserId = #UserId "
+ "ORDER BY eEnrolNo DESC;";
cmd = new OleDbCommand(strSql, mDB);
cmd.Parameters.Add("#UserId", OleDbType.Char).Value = strUserId;
mDB.Open();
rdr = cmd.ExecuteReader();
Boolean booRows = rdr.HasRows;
if (booRows) //when booRows is true, there are order records for the user
{
rdr.Read();
if ((string)rdr["eStatus"] != "Ordering") //status of an active order is "Ordering"
{
strOFlag = "M"; //"T" means there is a need to create a new Orders record
}
else { strOFlag = "M"; }
mDB.Close();
if (strOFlag == "M")
{
//insert a new order record
string strStatus = "Ordering";
strSql = "INSERT INTO enrolInfo (eUserId, eStatus) VALUES (#UserId, #Status)";
cmd = new OleDbCommand(strSql, mDB);
cmd.Parameters.AddWithValue("#UserId", strUserId);
cmd.Parameters.AddWithValue("#Status", strStatus);
mDB.Open();
cmd.ExecuteNonQuery();
mDB.Close();
}
//get back order No - this order no is needed when the user buys an item
strSql = "SELECT eEnrolNo FROM enrolInfo WHERE eUserId = #UserId "
+ "ORDER BY eEnrolNo DESC;";
cmd = new OleDbCommand(strSql, mDB);
cmd.Parameters.Add("#UserId", OleDbType.Char).Value = strUserId;
mDB.Open();
rdr = cmd.ExecuteReader();
rdr.Read();
Session["tOrderNo"] = rdr["eEnrolNo"]; //store the active order no in the sOrderNo
mDB.Close();
return;
}
}
This is the code that will route the solution to the DataRoutines file in my Register Page
//prepare Session variables for newly register customer
Session["sFlag"] = "M";
Session["tUserId"] = (string)txtUserId.Text;
Session["tName"] = (string)txtName.Text;
Session["tAddress"] = (string)txtAddress.Text;
Session["tTel"] = (string)txtTel.Text;
Session["tEmail"] = (string)txtEmail.Text;
String strUserId = (string)Session["tUserId"];
DataRoutines2 DRObject = new DataRoutines2();
DRObject.CreateRecs(strUserId);
Thanks for your help

"Variable names must be unique within a query batch or stored procedure." error c# asp.net

this is my code,when the textbox content changes the datas required have to retrieved from the databse and displayed in the labels specified.
protected void TextBox1_TextChanged(object sender, EventArgs e)
{
Match match = Regex.Match(TextBox1.Text, #"^\d{4}[A-Z]{5}\d{3}$");
if (match.Success)
{
try
{
DropDownList1.Focus();
string dpt = (string)Session["deptmnt"];
idd = TextBox1.Text;
Label33.Text = idd;
string val = idd;
string con = ConfigurationManager.ConnectionStrings["con"].ConnectionString;
SqlConnection con1 = new SqlConnection(con);
con1.Open();
// string val1 = dpt;
try
{
String str = "SELECT * from student where sid=#val";
SqlCommand cmd = new SqlCommand(str, con1);
cmd.CommandType = CommandType.Text;
SqlParameter sql;
cmd.Parameters.Clear();
sql = cmd.Parameters.Add("#val", SqlDbType.VarChar, 20);
sql.Value = val;
SqlDataReader reader = cmd.ExecuteReader();
if (reader.HasRows == false)
{
Label35.Visible = true;
TextBox1.Text = "";
}
else
{
{
Panel3.Visible = true;
DropDownList1.Focus();
while (reader.Read()) // if can read row from database
{
Panel3.Visible = true;
Label3.Text = reader["sname"].ToString();
Label5.Text = reader["dept"].ToString();
Label25.Text = reader["yr"].ToString();
}
cmd.Parameters.Clear();
{
string val1 = idd;
string str2 = "SELECT bid from studentissuebook where sid=#val1 AND status='" + "lost" + "'";
SqlCommand cmd2 = new SqlCommand(str2, con1);
cmd2.CommandType = CommandType.Text;
cmd2.Parameters.Clear();
SqlParameter sql2;
sql2 = cmd2.Parameters.Add("#val1", SqlDbType.VarChar, 20);
sql2.Value = val1;
SqlDataReader reader1 = cmd2.ExecuteReader();
if (reader1.HasRows == false)
{
TextBox1.Text = "";
Label39.Visible = true;
Panel3.Visible = false;
}
else
{
DropDownList1.Focus();
while (reader1.Read()) // if can read row from database
{
DropDownList1.Items.Add(reader1[0].ToString());
}
DropDownList1.Focus();
}
}
}
}
con1.Close();
}
catch(Exception ex)
{
TextBox1.Text=ex.ToString();
}
}
catch (Exception ex)
{
TextBox1.Text = ex.ToString();
}
} else
{
formatlabel.Visible = true;
}
}
but,when i run the code,i get an error "The variable name '#sid' has already been declared. Variable names must be unique within a query batch or stored procedure.",I googled, generally this error occurs when there is a for loop or any loops,but i do not have any loops in my code.so im unable to find the cause
Try using two separate connection and command objects, like this:
protected void TextBox1_TextChanged(object sender, EventArgs e)
{
Match match = Regex.Match(TextBox1.Text, #"^\d{4}[A-Z]{5}\d{3}$");
if (match.Success)
{
DropDownList1.Focus();
string dpt = (string) Session["deptmnt"];
idd = TextBox1.Text;
Label33.Text = idd;
string val = idd;
string con = ConfigurationManager.ConnectionStrings["con"].ConnectionString;
using (SqlConnection con1 = new SqlConnection(con))
{
String str = "SELECT * from student where sid=#val";
con1.Open();
using (SqlCommand cmd = new SqlCommand(str, con1))
{
cmd.CommandType = CommandType.Text;
SqlParameter sql;
cmd.Parameters.Clear();
sql = cmd.Parameters.Add("#val", SqlDbType.VarChar, 20);
sql.Value = val;
SqlDataReader reader = cmd.ExecuteReader();
if (reader.HasRows == false)
{
Label35.Visible = true;
TextBox1.Text = "";
}
else
{
Panel3.Visible = true;
DropDownList1.Focus();
while (reader.Read()) // if can read row from database
{
Panel3.Visible = true;
Label3.Text = reader["sname"].ToString();
Label5.Text = reader["dept"].ToString();
Label25.Text = reader["yr"].ToString();
}
cmd.Parameters.Clear();
}
}
}
using (SqlConnection con2 = new SqlConnection(con))
{
string val1 = idd;
string str2 = "SELECT bid from studentissuebook where sid=#val1 AND status='" + "lost" + "'";
con2.Open();
using (SqlCommand cmd2 = new SqlCommand(str2, con2))
{
cmd2.CommandType = CommandType.Text;
cmd2.Parameters.Clear();
SqlParameter sql2;
sql2 = cmd2.Parameters.Add("#val1", SqlDbType.VarChar, 20);
sql2.Value = val1;
SqlDataReader reader1 = cmd2.ExecuteReader();
if (reader1.HasRows == false)
{
TextBox1.Text = "";
Label39.Visible = true;
Panel3.Visible = false;
}
else
{
DropDownList1.Focus();
while (reader1.Read()) // if can read row from database
{
DropDownList1.Items.Add(reader1[0].ToString());
}
DropDownList1.Focus();
}
}
}
}
else
{
formatlabel.Visible = true;
}
}
Note: I have removed your try-catch blocks to make the code simpler to interpret, once it is working, then please re-apply your try-catch logic where you feel appropriate. Also, I added using blocks for the SqlConnection and SqlCommand objects, this will clean up the connection even if an exception happens.

ASP.net Control in FormView ItemTemplate

I have a DropDownList control in ItemTemplate of FormView_Product, how do I modify the code below to reference to my DropDownList1?
String strQty = DropDownList1.Items[DropDownList1.SelectedIndex].ToString();
Code
}
protected void btnBuy_Click(Object sender, EventArgs e)
{
// test to remind customer to login first
if ((string)Session["sFlag"] != "T")
{
Type csType = this.GetType();
ClientScript.RegisterStartupScript(csType, "Error", scriptErrorLogin);
}
else
{
// test to remind customer to login first
if ((string)Session["sFlag"] != "T")
{
Type csType = this.GetType();
ClientScript.RegisterStartupScript(csType, "Error", scriptErrorLogin);
}
else
{
OleDbConnection mDB = new OleDbConnection();
mDB.ConnectionString = "Provider = Microsoft.Jet.OLEDB.4.0;Data source="
+ Server.MapPath("~/App_Data/webBase.mdb");
OleDbCommand cmd;
//insert item purchased to itemsTable
int intOrderNo = (int)Session["sOrderNo"];
FormViewRow row0 = FormView_Product.Row;
String strProductId = ((Label)row0.FindControl("lblProductId")).Text;
Int32 unitPrice = Convert.ToInt32(((Label)row0.FindControl("lblUnitPrice")).Text);
float floUnitPrice = float.Parse(strUnitPrice);
String strQty = DropDownList1.Items[DropDownList1.SelectedIndex].ToString();
int intQty = int.Parse(strQty);
string strSQL = "INSERT INTO itemsTable(iOrderNo, iProductId, iQty, iUnitPrice)"
+ "VALUES (#OrderNo, #ProductId, #Qty, #UnitPrice)";
cmd = new OleDbCommand(strSQL, mDB);
cmd.Parameters.AddWithValue("#OrderNO", intOrderNo);
cmd.Parameters.AddWithValue("#ProductId", strProductId);
cmd.Parameters.AddWithValue("#Qty", intQty);
cmd.Parameters.AddWithValue("#UnitPrice", floUnitPrice);
mDB.Open();
cmd.ExecuteNonQuery();
mDB.Close();
Response.Redirect("ShoppingCart.aspx");
}
}
}
Try This
DropDownList DropDownList1 = (DropDownList)FormView_Product.FindControl("DropDownList1");
String strQty = DropDownList1.SelectedValue;

Categories