I am trying to retrieve column value from another table and inserting into another table but can't resolve it no error but unable to resolve it. Empty column appears. Trying to insert t_vrm in insert statement on sql_fix_01 t_vrm is a varchar in SQL Server and its a vehicle registration number (number plate)
But returns empty column.
private void btnProcess_Click(object sender, EventArgs e)
{
tbl = new DataTable();
tbl.Columns.Add(new DataColumn("ticket_reference", System.Type.GetType("System.String")));
tbl.Columns.Add(new DataColumn("ticket_number", System.Type.GetType("System.String")));
tbl.Columns.Add(new DataColumn("t_vrm", System.Type.GetType("System.String")));
tbl.Columns.Add(new DataColumn("sql_fix_01", System.Type.GetType("System.String")));
tbl.Columns.Add(new DataColumn("sql_fix_02", System.Type.GetType("System.String")));
tbl.Columns.Add(new DataColumn("sql_fix_03", System.Type.GetType("System.String")));
tbl.Columns.Add(new DataColumn("sql_fix_04", System.Type.GetType("System.String")));
SqlConnection myConn = new SqlConnection();
myConn.ConnectionString = stringConn;
SqlCommand myComm = new SqlCommand();
myComm.Connection = myConn;
string[] tempArray = new string[this.textBox1.Lines.Length];
tempArray = this.textBox1.Lines;
if (this.textBox1.Lines.Length == 0)
{
return;
}
myConn.Open();
int ticket_number = -666;
string t_vrm = "";
string sql_fix_01 = "";
string stringDatetime = DateTime.Now.ToString("yyyyMMdd HH:mm:ss");
//string stringDatetime = "20120829 17:00:00";
for (int counter = 0; counter <= tempArray.Length - 1; counter++)
{
sql_fix_01 = "";
t_vrm = "";
ticket_number = -666;
if (tempArray[counter].Trim().Length > 0)
{
try
{
myComm.CommandText = "SELECT t_number, t_vrm FROM tickets WHERE t_reference='" + tempArray[counter] + "'";
ticket_number = (int)myComm.ExecuteScalar();
t_vrm = (string)(myComm.ExecuteScalar()).ToString();
MY ERROR IS IN THIS ROW.(t_vrm)
sql_fix_01 = "INSERT INTO [dvla] ([dvla_system_ref],[dvla_seq_no],[dvla_vrm],[dvla_due],[dvla_sent],[dvla_sent_by],[dvla_batch_no],[dvla_response_date],[dvla_query_destination]) VALUES(" + ticket_number.ToString().Trim() + ", 2 , t_vrm , '" + stringDatetime + "', NULL,'',0, NULL, 'DVLATicketLetter');";
}
catch { }
if (ticket_number != -666)
{
tbl.Rows.Add(tempArray[counter], ticket_number,t_vrm, sql_fix_01, sql_fix_02, sql_fix_03, sql_fix_04);
}
}
}
myConn.Close();
this.dataGridView1.DataSource = tbl;
this.dataGridView1.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.AllCells;
DataView vwExport = new DataView(tbl);
if (sfd.ShowDialog() == DialogResult.OK)
{
if (sfd.FileName != "")
{
btnProcess.Enabled = false;
Application.DoEvents();
StreamWriter sw = null;
FileStream fs = null;
fs = File.Open(sfd.FileName, FileMode.Create, FileAccess.Write);
sw = new StreamWriter(fs, System.Text.Encoding.UTF8);
sw.WriteLine("USE ICPS");
sw.WriteLine("GO");
sw.WriteLine(" ");
sw.WriteLine("/* Set accounts Hold Status to ''VQ4 rescheduled' */");
sw.WriteLine(" ");
foreach (DataRowView drv in vwExport)
{
sw.WriteLine("/* Ticket Reference: " + drv["ticket_reference"].ToString() + "/" + drv["ticket_number"].ToString() + "/" + drv["t_vrm"].ToString() + "*/");
sw.WriteLine(drv["sql_fix_01"].ToString());
You cant use ExecuteScalar with multiple values..
myComm.CommandText = "SELECT t_number, t_vrm
FROM tickets WHERE t_reference='" + tempArray[counter] + "'";
ticket_number = (int)myComm.ExecuteScalar();
t_vrm = (string)(myComm.ExecuteScalar()).ToString();
You will need to use a DataReader instead.
SqlDataReader reader = myComm.ExecuteReader();
// Call Read before accessing data.
while (reader.Read())
{
ticket_number = reader.GetInt32(0);
t_vrm = reader.GetString(1);
}
Also, to reiterate what #Amber said, look at Bobby Tables, you really want to avoid dynamic SQL
Should'nt:
...VALUES(" + ticket_number.ToString().Trim() + ", 2 , t_vrm , '" +...
Be:
...VALUES(" + ticket_number.ToString().Trim() + ", 2 , " + t_vrm + " , '" +...
Your t_vrm variable is part of the string.
Related
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);
I have an Excel spreadsheet that I receive that I need to import into a table in our database. I have previously asked about pulling a single cell of data from a spreadsheet (Read a single cell from Excel to a string using C# and ASP.NET) and I am attempting to build off of this in order to move an entire spreadsheet into the database.
The format of the information is Column 1 = Name, Column 2 = Wage, Column 3 = Department
The existing code is as follows:
#region Initialize Connection
var Class_Connection = new SQL_Connection();
var sql = new SQL_Statements();
Class_Connection.cnn.Close();
#endregion
string properties = String.Format(#"Provider = Microsoft.ACE.OLEDB.12.0; Data Source = \\Hera\Public\LumberPrices\lbr_ems.xls; Extended Properties = 'Excel 8.0; HDR = NO;'");
string Price = "";
using (OleDbConnection conn = new OleDbConnection(properties))
{
string sqlpull = "SELECT * FROM [" + worksheet + "$" + Cell1 + ":" + Cell2 + "]";
conn.Open();
DataSet ds = new DataSet();
//string columns = String.Join(",", columnNames.ToArray());
using (OleDbDataAdapter da = new OleDbDataAdapter(sqlpull, properties))
{
string temp2 = "";
var dt = new DataTable();
da.Fill(dt);
for (int i = 0; i < dt.Columns.Count; i++)
{
temp2 = dt.Columns[i].ColumnName.ToString();
}
foreach (DataRow dr in dt.Rows)
{
Price = dr[temp2].ToString();
}
}
}
int Freight = GetFreight(LumbDesc);
int price1 = Convert.ToInt32(Price);
int addon = Convert.ToInt32(AddTo);
int Total = price1 + addon + Freight;
//TODO: insert into TLumberprice
string sqlStatement = "insert table([LumberCode], [Price], [PriceDate], [UserName], [Factor], [Op])" +
"values ('" + LumbDesc + "', '" + Total + "', '" + DateTime.Now + "', '" + LoginSession.userName.Remove(LoginSession.userName.Length - 1) + "', '" + Factor + "', '" + OP + "')";
#region Insert Lumber Prices
Class_Connection.cnn.Open();
SqlCommand InsertLumberPrices = new SqlCommand(sqlStatement, Class_Connection.cnn);
InsertLumberPrices.ExecuteNonQuery();
Class_Connection.cnn.Close();
#endregion
This works as intended. but I have questions.
Can I read the DataTable(dt) straight into the database, or do I have to use something like the following?
for (int i = 0; i < dt.Columns.Count; i++)
{
SName = dt.Columns[0].ColumnName.ToString();
SWage = dt.Columns[1].ColumnName.ToString();
SDept = dt.Columns[2].ColumnName.ToString();
}
foreach (DataRow dr in dt.Rows)
{
Name = dr[SName].tostring();
Wage = dr[SWage].tostring();
Dept = dr[SDept].tostring();
}
There is a way of importing the data from a data table into the SQL Table.
You need to use SqlBulkCopy
var sqlBulkCopy = new SqlBulkCopy(conn);
You can even map which data table column goes to which SQL Table column as well.
Here is an example.
using(var sqlBulkCopy = new SqlBulkCopy(conn))
{
sqlBulkCopy.ColumnMappings.Add(new SqlBulkCopyColumnMapping("Column 1", "Name"));
sqlBulkCopy.ColumnMappings.Add(new SqlBulkCopyColumnMapping("Column 2", "Wage"));
sqlBulkCopy.ColumnMappings.Add(new SqlBulkCopyColumnMapping("Column 3", "Department"));
sqlBulkCopy.DestinationTableName = "table" // table name in SQL
conn.Open();
sqlBulkCopy.WriteToServer(dt);
conn.Close();
}
Where conn is your SqlConnection.
If you don't want to use the data table, you could go directly to the BulkImport.
Just change the OleDbDataAdapter to OleDbCommand and put the value in an IDataReader variable, which then you can use in the code above instead of dt.
With the last part, I only did it in the past between 2 SQL servers that did not have a link to each other. I'm not sure 100% sure if it will work with OleDb.
So basically I have a C# project, that iterates through every student (300 students) within a table called Student within a Microsoft Access 2016 database. In a single iteration for a single student by using other tables like Mathematics, Reading that have a 1-to-1 relationship with the Student table, to grab the data that belongs to that student.
try
{
OleDbCommand allStudents = new OleDbCommand("SELECT [NSN]"
+ " FROM [Student]; ");
allStudents.Connection = conn;
OleDbDataAdapter allData = new OleDbDataAdapter(allStudents);
DataTable allTable = new DataTable();
allData.Fill(allTable);
foreach (DataRow dr in allTable.Rows)
{
string NSN = dr["NSN"].ToString();
OleDbCommand cmd = new OleDbCommand("SELECT * "
+ "FROM (((([Student] s "
+ "INNER JOIN [Student Extra] se ON se.[NSN] = s.[NSN]) "
+ "INNER JOIN [Reading] r ON r.[NSN] = s.[NSN])"
+ "INNER JOIN [Writing] w ON w.[NSN] = s.[NSN])"
+ "INNER JOIN [Mathematics] m ON m.[NSN] = s.[NSN]) "
+ "WHERE s.[NSN] = '" + NSN + "'; ");
cmd.Connection = conn;
OleDbDataAdapter daa = new OleDbDataAdapter(cmd);
DataTable dtt = new DataTable();
daa.Fill(dtt);
foreach (DataRow drr in dtt.Rows)
{
firstName = drr["Preferred Name"].ToString();
gender = drr["Gender"].ToString();
room = drr["Room Number"].ToString();
NSAchieve = drr["National Standard Achieve"].ToString();
NSProgress = drr["National Standard Progress"].ToString();
The above code is only a snippet of the code I have, but this is basically where the function will start.
By using this data, I want to be able to go through several SELECT statements for other tables and compare them and produce a calculated value.
Dictionary<string, OleDbCommand> d = new Dictionary<string, OleDbCommand>();
cmd = new OleDbCommand("SELECT [Achievement Statement]"
+ " FROM [National Standard Codes]"
+ " WHERE [National Standard Code] = '" + readingNSAchievementCode + "'; ");
d["readingNSAchievementOTJ"] = cmd;
cmd = new OleDbCommand("SELECT [" + NSAchieve + "]"
+ " FROM [Reading National Standards]"
+ " WHERE [Assessment] = '" + readingFinalAssessment + "'; ");
d["readingNSAchievementComp"] = cmd;
cmd = new OleDbCommand("SELECT [Timeframe]"
+ " FROM [Reading Statements]"
+ " WHERE [Year Code] = '" + NSProgress + "'; ");
d["readingNSProgressTimeframe"] = cmd;
There are several more commands, (approx <150). I use a Dictionary to store my Commands, and then execute the commands in a FOREACH loop.
foreach(KeyValuePair<string, OleDbCommand> pair in d)
{
try
{
string v = pair.Key;
OleDbCommand dbCmd = pair.Value;
dbCmd.Connection = conn;
OleDbDataReader reader = dbCmd.ExecuteReader();
reader.Read();
readingDict[v] = reader.GetString(0);
}
catch (Exception e)
{
MessageBox.Show("Error at " + pair.Key + "\n\n Here is message " + e);
}
}
After executing and getting my value, I want to store my data into another table called Calculated.
string insert1 = "INSERT INTO [Calculated] (";
int i = 0;
Dictionary<string, string> dict = createDictionary(NSN);
int len = dict.Count / 2;
foreach (KeyValuePair<string, string> pair in dict)
{
string field = pair.Key;
string value = pair.Value;
if (i == (len - 1))
{
insert1 += "[" + field + "])";
break;
}
else
{
insert1 += "[" + field + "], ";
}
i++;
}
insert1 += " VALUES (";
i = 0;
foreach (KeyValuePair<string, string> pair in dict)
{
string field = pair.Key;
string value = pair.Value;
if (i == len - 1)
{
insert1 += "'" + value + "')";
break;
}
else
{
insert1 += "'" + value + "', ";
}
i++;
}
I build my INSERT INTO query, and then I execute using an OleDbCommand. This needs to repeat 300 times, but for development purposes currently I only have 5 students in my Student table. However when executing after the 4th student it will always consistently give me an error System Resources Exceeded always at a specific OleDbCommand. I have tested each command separately, so there is no issue with the way the OleDbCommands are written.
I have tried searching on here, and tried to encase the first code snippet in a using statement, using using (OleDbConnection conn = new OleDbConnection(connectionStr)) but as I am still a novice at C#, I am unable to produce a solution.
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());
}
}
this is my sample code to check the data on Table1 using 2 filters, column1 and between data in column2. The code I have is working but is only getting 1 result. So for example. I enter "1" in textbox1, "3" in textbox2 and "6" in textbox3. Select * from TABLE1 where COLUMN1 = '1' AND COLUMN2 BETWEEN '3' AND '6' -- when run in sql result is 3,4,5,6 but in C# I am only getting "6". Can you help me with this to get "3,4,5,6" as a result. Thank you.
public partial class WebForm1 : System.Web.UI.Page
{
SqlConnection SC;
SqlCommand CMD;
SqlDataReader DR;
protected void Page_Load(object sender, EventArgs e)
{
}
protected void Button1_Click(object sender, EventArgs e)
{
SC = new SqlConnection(ConfigurationManager.ConnectionStrings["BABBLER"].ConnectionString);
SC.Open();
CMD = new SqlCommand("Select * from TABLE1 WHERE COLUMN1= '" + TextBox1.Text + "' and COLUMN2 Between '" + TextBox2.Text + "'" + " and " + "'" + TextBox3.Text + "'", SC);
DR = CMD.ExecuteReader();
if (DR.HasRows)
{
while (DR.Read())
{
label1.Text = DR["COLUMN2"].ToString();
}
}
}
}
}
Your loop is not appending the values, rather overwriting Label1. Change your while loop to
while (DR.Read())
{
label1.Text += DR["COLUMN2"].ToString() + ",";
}
if (label1.Text.EndsWith(",")) label1.Text = label1.Text.SubString(0, label1.Text.Length-1) //Remove the last comma
Change
label1.Text = DR["COLUMN2"].ToString();
as
label1.Text = label1.Text +", " + DR["COLUMN2"].ToString();
if (Label1.Text.Length > 2)
Label1.Text = Label1.Text.Substring(2);
try this code
SC = new SqlConnection(ConfigurationManager.ConnectionStrings["BABBLER"].ConnectionString);
SC.Open();
CMD = new SqlCommand("Select * from TABLE1 WHERE COLUMN1= '" + TextBox1.Text + "' and COLUMN2 Between '" + TextBox2.Text + "'" + " and " + "'" + TextBox3.Text + "'", SC);
DataSet ds = new DataSet();
SqlDataAdapter da = new SqlDataAdapter(CMD);
da.Fill(ds);
string data="";
for (int i = 0; i < ds.Tables[0].Rows.Count; i++ )
{
if(data=="")
{
label1.Text = ds.Tables[0].Rows[i]["COLUMN2"].ToString();
}
else
{
label1.Text +=","+ ds.Tables[0].Rows[i]["COLUMN2"].ToString();
}
}
There are a number of methods to combine results into a comma-separated list. However, using string concatenation should not be one - concatenating strings is slow, especially if you might have a large number of results. Try one of the following instead:
Using a StringBuilder
StringBuilder sb = new StringBuilder();
boolean doneFirstRow = false;
while (DR.READ())
{
if (doneFirstRow)
{
sb.Append(", ");
}
else
{
doneFirstRow = true;
}
sb.Append(dr["COLUMN2"].ToString());
}
Label1.Text = sb.ToString();
Using a List with String.Join:
List<string> values = new List<string>();
while (DR.READ())
{
values.Add(dr["COLUMN2"].ToString());
}
Label1.Text = String.Join(", ", values);
NB: If not using NET4.5 you'll need String.Join(", ", values.ToArray())