System.Data.SqlClient.SqlException: 'Invalid column name 'P1000'.' - c#

Can anybody help me? Why am I getting this error?
If I remove the 'P' from the prod_id which left only number, it can work but if I add alphabet, it says "Invalid column name".
I already added .ToString() to it, but why it still can't take varchar and only take int.
Here is my code
public partial class AddtoCart : System.Web.UI.Page
{
SqlConnection conn = new SqlConnection(Global.cs);
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
if (Session["Username"] == null)
{
Response.Redirect("Authentication.aspx");
}
// Adding product to Gridview
Session["addproduct"] = "false";
DataTable dt = new DataTable();
DataRow dr;
dt.Columns.Add("sno");
dt.Columns.Add("Id");
dt.Columns.Add("Pname");
dt.Columns.Add("Pimage");
dt.Columns.Add("Pprice");
dt.Columns.Add("Pquantity");
dt.Columns.Add("Ptotal");
if (Request.QueryString["Id"] != null)
{
if (Session["buyitems"] == null)
{
dr = dt.NewRow();
SqlConnection conn = new SqlConnection(Global.cs);
SqlDataAdapter da = new SqlDataAdapter("select * from Product2 where prod_id=" + Request.QueryString["Id"] , conn);
DataSet ds = new DataSet();
da.Fill(ds);
dr["sno"] = 1;
dr["Id"] = ds.Tables[0].Rows[0]["prod_id"].ToString();
dr["Pname"] = ds.Tables[0].Rows[0]["prod_name"].ToString();
dr["Pimage"] = ds.Tables[0].Rows[0]["prod_img"].ToString();
dr["Pprice"] = ds.Tables[0].Rows[0]["prod_price"].ToString();
dr["Pquantity"] = Request.QueryString["quantity"];
int price = Convert.ToInt32(ds.Tables[0].Rows[0]["prod_price"].ToString());
int Quantity = Convert.ToInt16(Request.QueryString["quantity"].ToString());
int TotalPrice = price * Quantity;
dr["Ptotal"] = TotalPrice;
dt.Rows.Add(dr);
conn.Open();
SqlCommand cmd = new SqlCommand("insert into Cart values('" + dr["sno"] + "','" + dr["Id"] + "','" + dr["Pname"] + "','" + dr["Pimage"] + "','" + dr["Pprice"] + "','" + dr["Pquantity"] + "','" + dr["Ptotal"] + "','" + Session["Username"].ToString() + "')", conn);
cmd.ExecuteNonQuery();
conn.Close();
GridView1.DataSource = dt;
GridView1.DataBind();
Session["buyitems"] = dt;
Button1.Enabled = true;
GridView1.FooterRow.Cells[5].Text = "Total Amount";
GridView1.FooterRow.Cells[6].Text = grandtotal().ToString();
Response.Redirect("AddtoCart.aspx");
}
else
{
dt = (DataTable)Session["buyitems"];
int sr;
sr = dt.Rows.Count;
dr = dt.NewRow();
SqlConnection conn = new SqlConnection(Global.cs);
SqlDataAdapter da = new SqlDataAdapter("select * from Product2 where prod_id=" + Request.QueryString["id"], conn);
DataSet ds = new DataSet();
da.Fill(ds);
dr["sno"] = sr + 1;
dr["Id"] = ds.Tables[0].Rows[0]["prod_id"].ToString();
dr["Pname"] = ds.Tables[0].Rows[0]["prod_name"].ToString();
dr["Pimage"] = ds.Tables[0].Rows[0]["prod_img"].ToString();
dr["Pprice"] = ds.Tables[0].Rows[0]["prod_price"].ToString();
dr["Pquantity"] = Request.QueryString["quantity"];
int price = Convert.ToInt32(ds.Tables[0].Rows[0]["prod_price"].ToString());
int Quantity = Convert.ToInt16(Request.QueryString["quantity"].ToString());
int TotalPrice = price * Quantity;
dr["Ptotal"] = TotalPrice;
dt.Rows.Add(dr);
conn.Open();
SqlCommand cmd = new SqlCommand("insert into Cart values('" + dr["sno"] + "','" + dr["Id"] + "','" + dr["Pname"] + "','" + dr["Pimage"] + "','" + dr["Pprice"] + "','" + dr["Pquantity"] + "','" + dr["Ptotal"] + "','" + Session["Username"].ToString() + "')", conn);
cmd.ExecuteNonQuery();
conn.Close();
GridView1.DataSource = dt;
GridView1.DataBind();
Session["buyitems"] = dt;
Button1.Enabled = true;
GridView1.FooterRow.Cells[5].Text = "Total Amount";
GridView1.FooterRow.Cells[6].Text = grandtotal().ToString();
Response.Redirect("AddtoCart.aspx");
}
}
else
{
dt = (DataTable)Session["buyitems"];
GridView1.DataSource = dt;
GridView1.DataBind();
if (GridView1.Rows.Count > 0)
{
GridView1.FooterRow.Cells[5].Text = "Total Amount";
GridView1.FooterRow.Cells[6].Text = grandtotal().ToString();
}
}
}
if (GridView1.Rows.Count.ToString() == "0")
{
Button3.Enabled = false;
Button1.Enabled = false;
}
else
{
Button3.Enabled = true;
Button1.Enabled = true;
}
}
// 2.Calculating Final Price
public int grandtotal()
{
DataTable dt = new DataTable();
dt = (DataTable)Session["buyitems"];
int nrow = dt.Rows.Count;
int i = 0;
int totalprice = 0;
while (i < nrow)
{
totalprice = totalprice + Convert.ToInt32(dt.Rows[i]["Ptotal"].ToString());
i = i + 1;
}
return totalprice;
}
// 4. Deleting Row From Cart
protected void GridView1_RowDeleting(object sender, GridViewDeleteEventArgs e)
{
DataTable dt = new DataTable();
dt = (DataTable)Session["buyitems"];
for (int i = 0; i <= dt.Rows.Count - 1; i++)
{
int sr;
int sr1;
string qdata;
string dtdata;
sr = Convert.ToInt32(dt.Rows[i]["sno"].ToString());
TableCell cell = GridView1.Rows[e.RowIndex].Cells[0];
qdata = cell.Text;
dtdata = sr.ToString();
sr1 = Convert.ToInt32(qdata);
TableCell prID = GridView1.Rows[e.RowIndex].Cells[1];
if (sr == sr1)
{
dt.Rows[i].Delete();
dt.AcceptChanges();
conn.Open();
SqlCommand cmd = new SqlCommand("Delete top (1) from Cart where product_id='" + prID.Text + "' and username= '" + Session["username"] + "' ", conn);
cmd.ExecuteNonQuery();
conn.Close();
//Item Has Been Deleted From Shopping Cart
break;
}
}
// 5. Setting SNo. after deleting Row item from cart
for (int i = 1; i <= dt.Rows.Count; i++)
{
dt.Rows[i - 1]["sno"] = i;
dt.AcceptChanges();
}
Session["buyitems"] = dt;
Response.Redirect("AddtoCart.aspx");
}
// 6. Button Click
protected void Button1_Click(object sender, EventArgs e)
{
bool isTrue = false;
DataTable dt = (DataTable)Session["buyitems"];
for (int i = 0; i <= dt.Rows.Count - 1; i++)
{
//SqlConnection conn = new SqlConnection(Global.cs);
//conn.Open();
//SqlCommand cmd = new SqlCommand("insert into Cart(sno,product_id,product_name,product_price,product_quantity,username) values('" + dt.Rows[i]["sno"] + "','" + dt.Rows[i]["Id"] + "','" + dt.Rows[i]["Pname"] + "','" + dt.Rows[i]["Pprice"] + "','" + dt.Rows[i]["Pquantity"] + "','" + Session["Username"] + "')", conn);
//cmd.ExecuteNonQuery();
//conn.Close();
int pId = Convert.ToInt16(dt.Rows[i]["Id"]);
int pQuantity = Convert.ToInt16(dt.Rows[i]["Pquantity"]);
SqlDataAdapter sda = new SqlDataAdapter("Select stock_count, prod_name from Product2 where prod_id='" + pId + "' ", conn);
DataTable dtble = new DataTable();
sda.Fill(dtble);
int quantity = Convert.ToInt16(dtble.Rows[0][0]);
if(quantity == 0)
{
string pName = dtble.Rows[0][1].ToString();
string msg = "" + pName + " is not in Stock";
Response.Write("<script>alert('" + msg + "');</script>");
isTrue = false;
}
}
if (GridView1.Rows.Count.ToString() == "0")
{
Response.Write("<script>alert('Your Cart is Empty. You cannot place an Order');</script>");
}
else
{
if (isTrue == true)
{
Response.Redirect("Checkout2.aspx");
}
}
// If Session is Null Redirecting to login else Placing the order
if (Session["Username"] == null)
{
Response.Redirect("Authentication.aspx");
}
else
{
Response.Redirect("Checkout2.aspx");
}
}
public void clearCart()
{
conn.Open();
SqlCommand cmd = new SqlCommand("Delete from Cart where username='" + Session["Username"] + "' ", conn);
cmd.ExecuteNonQuery();
conn.Close();
Response.Redirect("AddtoCart.aspx");
}
protected void Button3_Click(object sender, EventArgs e)
{
Session["buyitems"] = null;
clearCart();
}
}
This is the database table
CREATE TABLE [dbo].[Product2]
(
[prod_id] VARCHAR(6) NOT NULL,
[prod_name] VARCHAR(50) NOT NULL,
[prod_price] FLOAT(53) NOT NULL,
[prod_desc] VARCHAR(120) NOT NULL,
[prod_img] NVARCHAR(MAX) NOT NULL,
[prod_cat] VARCHAR(6) NOT NULL,
[stock_count] INT NULL,
[weight] DECIMAL(9, 2) NULL,
[width] DECIMAL(9, 2) NULL,
[length] DECIMAL(9, 2) NULL,
[height] DECIMAL(9, 2) NULL,
[shipping_fee] DECIMAL(9, 2) NOT NULL,
[created_at] DATETIME NOT NULL,
[updated_at] DATETIME NULL,
[prod_status] NVARCHAR(MAX) NULL,
PRIMARY KEY CLUSTERED ([prod_id] ASC),
CONSTRAINT [FK_Product2_ToTable]
FOREIGN KEY ([prod_cat]) REFERENCES [dbo].[Category] ([cat_id])
);

The way you pass the query could lead to SQL Injection.
SqlDataAdapter da = new SqlDataAdapter("select * from Product2 where prod_id=" + Request.QueryString["Id"] , conn);
I expect the final query you want to achieve is
select * from Product2 where prod_id=`P100`
But after revise your code if you do concatenate with 'P' in your query, you will get:
select * from Product2 where prod_id=P100
In which this will return result:
Invalid column name 'P100'
String concatenation into query is dangerous that possible break your query.
You need to create a SqlCommand variable and pass it to the SqlDataAdapter.
And also use SqlParameter to pass the parameter value.
SqlCommand cmd = new SqlCommand("select * from Product2 where prod_id = #Prod_ID", con);
cmd.Parameters.Add("#Prod_ID", SqlDbType.Varchar, 6).Value = "P" + Request.QueryString["id"].ToString;
After create and initialize SqlCommand, then you pass it into SqlDataAdpater as below
SqlDataAdapter da = new SqlDataAdapter(cmd);
Additional recommendation:
Use using block for your SqlConnection, SqlCommand and SqlDataAdapter as these (implemented with IDisposable interface) will automatically dispose the resources once the process is ended or exception is triggered.
DataSet ds = new DataSet();
using (SqlConnection conn = new SqlConnection(Global.cs))
{
using (SqlCommand cmd = new SqlCommand("select * from Product2 where prod_id = #Prod_ID", con))
{
cmd.Parameters.Add("#Prod_ID", SqlDbType.Varchar, 6).Value = "P" + Request.QueryString["id"].ToString;
using (SqlDataAdapter da = new SqlDataAdapter(cmd))
{
da.Fill(ds);
}
}
}
Updated answer with credited to #Tim Schmelter's suggestion
For Using declarations in C#8.0, you are not required to add scope for the using block.
A using declaration is a variable declaration preceded by the using keyword. It tells the compiler that the variable being declared should be disposed at the end of the enclosing scope.
DataSet ds = new DataSet();
using SqlConnection conn = new SqlConnection(Global.cs);
using SqlCommand cmd = new SqlCommand("select * from Product2 where prod_id = #Prod_ID", con);
cmd.Parameters.Add("#Prod_ID", SqlDbType.Varchar, 6).Value = "P" + Request.QueryString["id"].ToString;
using SqlDataAdapter da = new SqlDataAdapter(cmd);
da.Fill(ds);

Related

How to fix System.IndexOutOfRangeException: Cannot find table 0 ASP.NET

[WebMethod()]
public DataTable insert_data_to_db_from_local(string partnumber, string srctcode, string dockcode,int pack,string error,string chk,string user,DateTime day,string ekb,string kbid)
{
SqlConnection objConn = new SqlConnection();
SqlCommand objCmd = new SqlCommand();
SqlDataAdapter dtAdapter = new SqlDataAdapter();
DataSet ds = new DataSet();
DataTable dt = null;
string strConnString = null;
StringBuilder strSQL = new StringBuilder();
strConnString = "Server=localhost;UID=sa;PASSWORD=12345678;database=bds_pp_srct;Max Pool Size=400;Connect Timeout=600;";
strSQL.Append("INSERT INTO Hanheld (Part_Number,SRCT_Code,Dock_Code,Package,Error_Code,Chk_Type,LogUser,LogDate,ekb_order_no,Kanban_ID) VALUES ('" + partnumber + "','" + srctcode + "','" + dockcode + "','" + pack + "','" + error + "','" + chk + "','" + user + "','" + day + "','" + ekb + "','" + kbid + "') ");
//strSQL.Append(" WHERE [SRCT_Code] = '" + strCusID + "' ");
objConn.ConnectionString = strConnString;
var _with1 = objCmd;
_with1.Connection = objConn;
_with1.CommandText = strSQL.ToString();
_with1.CommandType = CommandType.Text;
dtAdapter.SelectCommand = objCmd;
dtAdapter.Fill(ds);
dt = ds.Tables[0];
dtAdapter = null;
objConn.Close();
objConn = null;
return dt;
}
This error :
System.IndexOutOfRangeException: Cannot find table 0.
at System.Data.DataTableCollection.get_Item(Int32 index)
Try this one
private DataTable dataTable = new DataTable();
string connString = #"query string here";
string query = "select table";
SqlConnection conn = new SqlConnection(connString);
SqlCommand cmd = new SqlCommand(query, conn);
conn.Open();
SqlDataAdapter da = new SqlDataAdapter(cmd);
da.Fill(dataTable);
conn.Close();
da.Dispose();
I think you are using DataSet in your code might be there would be a problem
so you first need to check where that DataSet contains datatable at 0 location
eg.
DataSet ds = new DataSet();
dtAdapter.Fill(ds);
if(ds != null && ds.Tables.Count > 0) {
//your logic
}
[WebMethod()]
public void insert_data_to_db_from_local(string partnumber, string srctcode, string dockcode)
{
using (SqlConnection conn = new SqlConnection("Server=localhost;UID=sa;PASSWORD=12345678;database=Test;Max Pool Size=400;Connect Timeout=600;"))
{
using (SqlCommand cmd = new SqlCommand())
{
cmd.Connection = conn;
cmd.CommandType = CommandType.Text;
cmd.CommandText = #"INSERT INTO Hanheld(Part_Number,SRCT_Code,Dock_Code) VALUES(#partnumber,#srctcode,#dockcode)";
cmd.Parameters.AddWithValue("#partnumber", partnumber);
cmd.Parameters.AddWithValue("#srctcode", srctcode);
cmd.Parameters.AddWithValue("#dockcode", dockcode);
try
{
conn.Open();
cmd.ExecuteNonQuery();
}
catch (SqlException e)
{
// MessgeBox.Show(e.Message.ToString(), "Error Message");
}
}
}
}
This my Be fixed

how to add the value in a variable to a datatable

I have a DataTable called datatablebuy. I need to insert a value called avg to the DataTable and display it in the girdview. I have obtained the value for datatablebuy from database called transac. How can I add the value in the variable "avg" to the datatablebuy. I am using C# for coding, The code looks as follows :
protected void Button1_Click(object sender, EventArgs e)
{
try
{
SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString);
conn.Open();
var sql = #"select scriptname,accnum,Quantity,price from transac where transactio = 'Sell' and scriptname = '" + TextBox2.Text + "' and accnum ='" + TextBox1.Text + "'";
var sqll = #"select scriptname,accnum,Quantity,price from transac where transactio = 'Buy' and scriptname ='" + TextBox2.Text + "' and accnum ='" + TextBox1.Text + "'";
var da = new SqlDataAdapter(sqll, conn);
var dataTablebuy = new DataTable();
da.Fill(dataTablebuy);
var dataAdapter = new SqlDataAdapter(sql, conn);
var dataTablesell = new DataTable();
dataAdapter.Fill(dataTablesell);
foreach (DataRow row in dataTablesell.Rows)
{
foreach (DataRow rw in dataTablebuy.Rows)
{
if (double.Parse(rw["Quantity"].ToString()) > double.Parse(row["Quantity"].ToString()))
{
rw["Quantity"] = double.Parse(rw["Quantity"].ToString()) - double.Parse(row["Quantity"].ToString());
row["Quantity"] = 0;
}
else
{
row["Quantity"] = double.Parse(row["Quantity"].ToString()) - double.Parse(rw["Quantity"].ToString());
rw["Quantity"] = 0;
}
}
}
float denom = 0;
float numer = 0;
float avg = 0;
foreach (DataRow rw in dataTablebuy.Rows)
{
denom = denom + int.Parse(rw["Quantity"].ToString());
numer = numer + (int.Parse(rw["Quantity"].ToString()) * int.Parse(rw["price"].ToString()));
avg = numer / denom;
}
GridView1.DataSource = dataTablebuy;
GridView1.DataBind();
ViewState["dataTablebuy"] = dataTablebuy;
GridView1.Visible = true;
Response.Write("average " +avg.ToString());
}
catch (System.Data.SqlClient.SqlException sqlEx)
{
Response.Write("error" + sqlEx.ToString());
}
catch (Exception ex)
{
Response.Write("error" + ex.ToString());
}
}
after
dataAdapter.Fill(dataTablesell);
you have to add column to DataTable like this
dataTablesell.Columns.Add("avg",typeof(decimal));
then inside
foreach (DataRow row in dataTablesell.Rows)
{
foreach (DataRow rw in dataTablebuy.Rows)
{
row["avg"]=0;
//set your avg value here
}
}
dataTablebuy.Columns.Add("avg", typeof(int));
foreach (DataRow rw in dataTablebuy.Rows)
{
rw["avg"] = //Pleaase assign average value here
}
i hope this will work.
First add avg column into your dataTablebuy DataTable then assign your avg variable to avg column.
protected void Button1_Click(object sender, EventArgs e)
{
try
{
SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString);
conn.Open();
var sql = #"select scriptname,accnum,Quantity,price from transac where transactio = 'Sell' and scriptname = '" + TextBox2.Text + "' and accnum ='" + TextBox1.Text + "'";
var sqll = #"select scriptname,accnum,Quantity,price from transac where transactio = 'Buy' and scriptname ='" + TextBox2.Text + "' and accnum ='" + TextBox1.Text + "'";
var da = new SqlDataAdapter(sqll, conn);
var dataTablebuy = new DataTable();
da.Fill(dataTablebuy);
dataTableBuy.Columns.Add("Avg",typeof(float));
var dataAdapter = new SqlDataAdapter(sql, conn);
var dataTablesell = new DataTable();
dataAdapter.Fill(dataTablesell);
foreach (DataRow row in dataTablesell.Rows)
{
foreach (DataRow rw in dataTablebuy.Rows)
{
if (double.Parse(rw["Quantity"].ToString()) > double.Parse(row["Quantity"].ToString()))
{
rw["Quantity"] = double.Parse(rw["Quantity"].ToString()) - double.Parse(row["Quantity"].ToString());
row["Quantity"] = 0;
}
else
{
row["Quantity"] = double.Parse(row["Quantity"].ToString()) - double.Parse(rw["Quantity"].ToString());
rw["Quantity"] = 0;
}
}
}
float denom = 0;
float numer = 0;
float avg = 0;
foreach (DataRow rw in dataTablebuy.Rows)
{
denom = denom + int.Parse(rw["Quantity"].ToString());
numer = numer + (int.Parse(rw["Quantity"].ToString()) * int.Parse(rw["price"].ToString()));
avg = numer / denom;
rw["Avg"] = avg;
}
GridView1.DataSource = dataTablebuy;
GridView1.DataBind();
ViewState["dataTablebuy"] = dataTablebuy;
GridView1.Visible = true;
Response.Write("average " +avg.ToString());
}
catch (System.Data.SqlClient.SqlException sqlEx)
{
Response.Write("error" + sqlEx.ToString());
}
catch (Exception ex)
{
Response.Write("error" + ex.ToString());
}
}

DataGrid View Not Showing Newly Added Record using Access Database

I am new to C# and I want to do this ASAP as I've had this problem since past week. I have tried a few approaches and not yet gotten the correct output. Here is my code:
private void btnDelete_Click(object sender, EventArgs e)
{
try
{
String itemcode = tbItemCode.Text.ToString();
String shade = tbShade.Text.ToString();
String rollnumber = tbRollNumber.Text.ToString();
System.Data.OleDb.OleDbConnection conn = new System.Data.OleDb.OleDbConnection(#"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\Users\Eranga\Documents\Visual Studio 2010\Projects\RollAllocationModel\RollAllocationModel\Roll.mdb;Persist Security Info=True;Jet OLEDB:Database Password=admin");
String deletequery = "DELETE FROM TabRoll WHERE (ItemCode = '" + itemcode + "') AND (Shade = '" + shade + "') AND (RollNumber = '" + rollnumber + "')";
//String deletequery = "SELECT * FROM TabRoll";
//code by query builder ----> DELETE FROM TabRoll WHERE (ItemCode = '" + itemcode + "') AND (Shade = '" + shade + "') AND (RollNumber = '" + length + "');
conn.Open();
OleDbDataAdapter da = new OleDbDataAdapter(deletequery, conn);
OleDbCommandBuilder cb = new OleDbCommandBuilder(da);
DataTable dt = new DataTable();
da.Fill(dt);
BindingSource bSource = new BindingSource();
bSource.DataSource = dt;
dataGridView1.EndEdit();
bSource.EndEdit();
da.Update(dt);
dataGridView1.DataSource = bSource;
conn.Close();
MessageBox.Show("Data deleted");
}
catch (Exception exceptionObj)
{
MessageBox.Show(exceptionObj.Message.ToString());
}
}
Why doesn't the DataGrid does not update with the new record.

Update, Insert to sql .. There is already an open DataReader associated with

string[] stringList2 = new string[10];
if (VaildDataRow == true)
{
//Response.Write("<script>alert('2valid data row" + TbRow + "')</script>");
TbCol = 0;
TcCol = 1;
foreach (TableCell tc in tr.Cells)
{
#region //Load array with valid row text boxes' value
foreach (Control c1 in tc.Controls)
{
if (c1 is TextBox)
{
if (c1.ID.StartsWith("DataTbFld_"))
{
TextBox txt = (TextBox)t11.FindControl(c1.ID);
if (string.IsNullOrEmpty(txt.Text))
{
//Response.Write("<script>alert('txt#id ..not hidden..: " + txt.ID + " found data in textbox, rec is valid , will break')</script>");
txt.Text="Null";
}
stringList2[TbCol] = txt.Text.ToString();
//Response.Write("<script>alert('TbRow : " + TbRow + " TcCol : " + TcCol + " TbCol : " + TbCol + " txt.Text.ToString() : " + txt.Text.ToString() + "')</script>");
}
TbCol += 1;
}
}
#endregion//===
TcCol += 1;
}
Response.Write("<script>alert('TbRow : " + TbRow + "')</script>");
#region //if exist update else insert
Response.Write("<script>alert('InputDate = " + stringList2[6] +
" and Dept= " + stringList2[7] + " and DeptType= " + stringList2[8] +
" and DeptSubType= " + stringList2[9] + "')</script>");
con.Open();
cmd = new SqlCommand("SELECT * FROM MainDailyData WHERE Dept= '" + stringList2[7] + "' and DeptType = '" + stringList2[8] + "' and DeptSubType= '" + stringList2[9] + "'", con);
dr = cmd.ExecuteReader();
if (dr != null && dr.HasRows)
{
Response.Write("<script>alert('Found,Update')</script>");
SqlDataAdapter myda = new SqlDataAdapter();
myda.UpdateCommand = new SqlCommand("UPDATE MainDailyData SET Product1 = #Prod1, Product2 = #Prod2, Product3 = #Prod3, Product4 = #Prod4, Product5 = #Prod5, Product6 = #Prod6, InputDate = #InDate, Dept = #Dpt, DeptType = #DptType, DeptSubType = #DptSubType", con);
myda.UpdateCommand.Parameters.Add("#Prod1", SqlDbType.VarChar).Value = stringList2[0];
myda.UpdateCommand.Parameters.Add("#Prod2", SqlDbType.VarChar).Value = stringList2[1];
myda.UpdateCommand.Parameters.Add("#Prod3", SqlDbType.VarChar).Value = stringList2[2];
myda.UpdateCommand.Parameters.Add("#Prod4", SqlDbType.VarChar).Value = stringList2[3];
myda.UpdateCommand.Parameters.Add("#Prod5", SqlDbType.VarChar).Value = stringList2[4];
myda.UpdateCommand.Parameters.Add("#Prod6", SqlDbType.VarChar).Value = stringList2[5];
myda.UpdateCommand.Parameters.Add("#InDate", SqlDbType.VarChar).Value = stringList2[6];
myda.UpdateCommand.Parameters.Add("#Dpt", SqlDbType.VarChar).Value = stringList2[7];
myda.UpdateCommand.Parameters.Add("#DptType", SqlDbType.VarChar).Value = stringList2[8];
myda.UpdateCommand.Parameters.Add("#DptSubType", SqlDbType.VarChar).Value = stringList2[9];
//dr.Close();
//con.Open();
myda.UpdateCommand.ExecuteNonQuery();
}
else
{
Response.Write("<script>alert('not Found,Insert')</script>");
SqlDataAdapter myda = new SqlDataAdapter();
myda.InsertCommand = new SqlCommand("INSERT INTO MainDailyData (Product1,Product2,Product3,Product4,Product5,Product6,InputDate,Dept,DeptType,DeptSubType) VALUES(#Prod1,#Prod2,#Prod3,#Prod4,#Prod5,#Prod6,#InDate,#Dpt,#DptType,#DptSubType)", con);
myda.InsertCommand.Parameters.Add("#Prod1", SqlDbType.VarChar).Value = stringList2[0];
myda.InsertCommand.Parameters.Add("#Prod2", SqlDbType.VarChar).Value = stringList2[1];
myda.InsertCommand.Parameters.Add("#Prod3", SqlDbType.VarChar).Value = stringList2[2];
myda.InsertCommand.Parameters.Add("#Prod4", SqlDbType.VarChar).Value = stringList2[3];
myda.InsertCommand.Parameters.Add("#Prod5", SqlDbType.VarChar).Value = stringList2[4];
myda.InsertCommand.Parameters.Add("#Prod6", SqlDbType.VarChar).Value = stringList2[5];
myda.InsertCommand.Parameters.Add("#InDate", SqlDbType.VarChar).Value = stringList2[6];
myda.InsertCommand.Parameters.Add("#Dpt", SqlDbType.VarChar).Value = stringList2[7];
myda.InsertCommand.Parameters.Add("#DptType", SqlDbType.VarChar).Value = stringList2[8];
myda.InsertCommand.Parameters.Add("#DptSubType", SqlDbType.VarChar).Value = stringList2[9];
//dr.Close();
//con.Open();
myda.InsertCommand.ExecuteNonQuery();
}
con.Close();
#endregion
}
#endregion
TbRow += 1;
}
when excauting
myda.InsertCommand.ExecuteNonQuery();
or
myda.UpdateCommand.ExecuteNonQuery();
i got error msg
There is already an open DataReader associated with this Command which must be closed first
if I close dr the result will be messy. If it found record in row 2 of the table, it will insert record of row 1 from the table to the database
i tried to enable MultipleActiveResultSets="true", but i got a problem attribute is not allowed!
I want to check if record exist, update else ,insert. how to achieve this or how to correct my code?
after edition:
#region //if exist update else insert inserting code
//Response.Write("<script>alert('InputDate = " + stringList2[6] +
//" and Dept= " + stringList2[7] + " and DeptType= " + stringList2[8] +
//" and DeptSubType= " + stringList2[9] + "')</script>");
con.Open();
//cmd = new SqlCommand("SELECT 1 FROM MainDailyData WHERE Dept= '" + stringList2[7] +
// "' and DeptType = '" + stringList2[8] + "' and DeptSubType= '" + stringList2[9] + "'", con);
cmd = new SqlCommand("SELECT 1 FROM MainDailyData WHERE Dept= #dpt and DeptType = #dptType and DeptSubType= #DptSbType", con);
cmd.Parameters.AddWithValue("#dpt", stringList2[7]);
cmd.Parameters.AddWithValue("#dptType", stringList2[8]);
cmd.Parameters.AddWithValue("#DptSbType", stringList2[9]);
bool fRecordExists = false;
SqlDataReader dr = cmd.ExecuteReader();
//SqlDataReader dr = cmd.ExecuteScalar();
if (dr != null && dr.HasRows)
{
fRecordExists = true;
}
dr.Close();
dr.Dispose();
if (fRecordExists)
{
Response.Write("<script>alert('Found,Update')</script>");
SqlDataAdapter myda = new SqlDataAdapter();
myda.UpdateCommand = new SqlCommand("UPDATE MainDailyData SET Product1 = #Prod1, Product2 = #Prod2, Product3 = #Prod3, Product4 = #Prod4, Product5 = #Prod5, Product6 = #Prod6, InputDate = #InDate, Dept = #Dpt, DeptType = #DptType, DeptSubType = #DptSubType", con);
myda.UpdateCommand.Parameters.Add("#Prod1", SqlDbType.VarChar).Value = stringList2[0];
myda.UpdateCommand.Parameters.Add("#Prod2", SqlDbType.VarChar).Value = stringList2[1];
myda.UpdateCommand.Parameters.Add("#Prod3", SqlDbType.VarChar).Value = stringList2[2];
myda.UpdateCommand.Parameters.Add("#Prod4", SqlDbType.VarChar).Value = stringList2[3];
myda.UpdateCommand.Parameters.Add("#Prod5", SqlDbType.VarChar).Value = stringList2[4];
myda.UpdateCommand.Parameters.Add("#Prod6", SqlDbType.VarChar).Value = stringList2[5];
myda.UpdateCommand.Parameters.Add("#InDate", SqlDbType.VarChar).Value = stringList2[6];
myda.UpdateCommand.Parameters.Add("#Dpt", SqlDbType.VarChar).Value = stringList2[7];
myda.UpdateCommand.Parameters.Add("#DptType", SqlDbType.VarChar).Value = stringList2[8];
myda.UpdateCommand.Parameters.Add("#DptSubType", SqlDbType.VarChar).Value = stringList2[9];
myda.UpdateCommand.ExecuteNonQuery();
}
else
{
Response.Write("<script>alert('not Found,Insert')</script>");
SqlDataAdapter myda = new SqlDataAdapter();
myda.InsertCommand = new SqlCommand("INSERT INTO MainDailyData (Product1,Product2,Product3,Product4,Product5,Product6,InputDate,Dept,DeptType,DeptSubType) VALUES(#Prod1,#Prod2,#Prod3,#Prod4,#Prod5,#Prod6,#InDate,#Dpt,#DptType,#DptSubType)", con);
myda.InsertCommand.Parameters.Add("#Prod1", SqlDbType.VarChar).Value = stringList2[0];
myda.InsertCommand.Parameters.Add("#Prod2", SqlDbType.VarChar).Value = stringList2[1];
myda.InsertCommand.Parameters.Add("#Prod3", SqlDbType.VarChar).Value = stringList2[2];
myda.InsertCommand.Parameters.Add("#Prod4", SqlDbType.VarChar).Value = stringList2[3];
myda.InsertCommand.Parameters.Add("#Prod5", SqlDbType.VarChar).Value = stringList2[4];
myda.InsertCommand.Parameters.Add("#Prod6", SqlDbType.VarChar).Value = stringList2[5];
myda.InsertCommand.Parameters.Add("#InDate", SqlDbType.VarChar).Value = stringList2[6];
myda.InsertCommand.Parameters.Add("#Dpt", SqlDbType.VarChar).Value = stringList2[7];
myda.InsertCommand.Parameters.Add("#DptType", SqlDbType.VarChar).Value = stringList2[8];
myda.InsertCommand.Parameters.Add("#DptSubType", SqlDbType.VarChar).Value = stringList2[9];
myda.InsertCommand.ExecuteNonQuery();
}
con.Close();
#endregion
still the problem exist for updating or inserting the second row, if i fill 1st first record and leave the second empty, it will insert it to the db but will not eccept any inserting later to the second row, instead it will duplicate the 1st row record. interchangablly, for if i fill the the second row first. if i fill both if them # the begining it will insert them both but will not recognize the second record and will duplicate the first record?
Just close the dr immediately after you determine whether or not it has any results; you aren't using it for anything other than determining if the record exists or not, so this won't affect your logic at all.
Replace:
dr = cmd.ExecuteReader();
if (dr != null && dr.HasRows)
with:
bool fRecordExists = false;
dr = cmd.ExecuteReader();
if (dr != null && dr.HasRows)
{
fRecordExists = true;
}
dr.Close();
if (fRecordExists)
You should also change the select statement to a parameterized query to prevent SQL injection attacks and exceptions due to unexpected characters in the data.
Also, the select statement, if it isn't going to be used for anything other than existence verification, should just do SELECT 1 instead of SELECT * to prevent unneeded processing in both the database and application.
Finally, if your application data supports it (i.e. the select criteria will only select 1 record at the max), I would suggest using ExecuteScalar instead of ExecuteReader, which would eliminate your problem altogether.

import xml to mdb

I'm trying to export a SQL-Server query to an XML file now and I want to import that file to Access. I don't understand how to do this.
Here is the code I use to generate the XML:
protected void Button1_Click(object sender, EventArgs e) {
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["SqlSconn"].ConnectionString);
con.Open();
string strSQL = "select * from dbo.table_"+test.Text.ToString()+"";
SqlDataAdapter dt = new SqlDataAdapter(strSQL, con);
DataSet ds = new DataSet();
dt.Fill(ds, "" + test.Text.ToString() + "");
ds.WriteXml(Server.MapPath("temp.xml"));
}
This may be a start.
static void SaveToMDB(DataSet ds, string strMDBFile)
{
OleDbConnection cAccess = new OleDbConnection(
"Provider=Microsoft.Jet.OLEDB.4.0;Data source=" + strMDBFile);
cAccess.Open();
foreach (DataTable oTable in ds.Tables)
{
OleDbCommand oCommand = new OleDbCommand(
"DROP TABLE [" + oTable.TableName + "]", cAccess);
try
{
oCommand.ExecuteNonQuery();
}
catch (Exception) { }
string strCreateColumns = "";
string strColumnList = "";
string strQuestionList = "";
foreach (DataColumn oColumn in oTable.Columns)
{
strCreateColumns += "[" + oColumn.ColumnName + "] VarChar(255), ";
strColumnList += "[" + oColumn.ColumnName + "],";
strQuestionList += "?,";
}
strCreateColumns = strCreateColumns.Remove(strCreateColumns.Length - 2);
strColumnList = strColumnList.Remove(strColumnList.Length - 1);
strQuestionList = strQuestionList.Remove(strQuestionList.Length - 1);
oCommand = new OleDbCommand("CREATE TABLE [" + oTable.TableName
+ "] (" + strCreateColumns + ")", cAccess);
oCommand.ExecuteNonQuery();
OleDbDataAdapter da = new OleDbDataAdapter(
"SELECT * FROM [" + oTable.TableName + "]", cAccess);
da.MissingSchemaAction = MissingSchemaAction.Add;
da.FillLoadOption = LoadOption.OverwriteChanges;
da.InsertCommand = new OleDbCommand(
"INSERT INTO [" + oTable.TableName + "] (" + strColumnList
+ ") VALUES (" + strQuestionList + ")", cAccess);
foreach (DataColumn oColumn in oTable.Columns)
{
da.InsertCommand.Parameters.Add(
oColumn.ColumnName,
OleDbType.VarChar,
255,
oColumn.ColumnName
);
}
foreach (DataRow oRow in oTable.Rows)
oRow.SetAdded();
da.Update(oTable);
}
}
This Data will work only with ID and Name, using the system :
using System;using System.Collections.Generic;using System.Linq;using System.Web;using System.Web.UI;using System.Web.UI.WebControls;using System.Data.Sql;using System.Data.SqlClient;using System.Configuration;using System.Data;using System.IO;
using System.Xml.Linq;
//import SelectiveDatabaseBackup.xml to test9 table
string connectionString = ConfigurationManager.ConnectionStrings["ApplicationServices3"].ConnectionString;
SqlConnection sqlConnection1 = new SqlConnection(connectionString);
SqlCommand cmd = new SqlCommand();
cmd.CommandType = CommandType.Text;
DataSet ds = new DataSet();
ds.ReadXml(XDocument.Load("c:/d/SelectiveDatabaseBackup.xml").CreateReader());
foreach (DataTable table in ds.Tables)
{
//Create table
foreach (DataRow row in table.Rows)
{
string name = row[1].ToString();
string id = row[0].ToString();
cmd.CommandText = "INSERT test9 VALUES ('"+ id +"','"+ name + "')";
cmd.Connection = sqlConnection1;
sqlConnection1.Open();
cmd.ExecuteNonQuery();
sqlConnection1.Close();
}
}
//--------------------------

Categories

Resources