Convert InnerHtml values into Decimal - c#

Im trying to convert InnerHtml values to Decimal value. The user will input an XPath into textBox2
List<Decimal> productPriceList = new List<Decimal>();
var priceTags = document.DocumentNode.SelectNodes(textBox2.Text);
Then I do a foreach loop to iterate though the prices found and add them to a list called productPriceList
foreach (var prices in priceTags)
{
label9.Visible = true;
label9.Text += prices.InnerHtml + "\n";
productPriceList.Add(prices.InnerHtml);
label2.Visible = false;
label3.Visible = false;
}
Then I add the values into the database:
using (var con = new SqlConnection(connectionString))
{
con.Open();
using (var cmd = new SqlCommand(#"INSERT INTO OnlineProductsTemp$(CompetitorID, ProductCode, ProductName, DateCaptured)
VALUES(#CompetitorID, #ProductCode, #ProductName, #DateCaptured)", con))
{
cmd.Parameters.Add("#CompetitorID", SqlDbType.Int);
cmd.Parameters.Add("#ProductCode", SqlDbType.VarChar);
cmd.Parameters.Add("#ProductName", SqlDbType.VarChar);
cmd.Parameters.Add("#Price", SqlDbType.Decimal);
cmd.Parameters.Add("#DateCaptured", SqlDbType.DateTime);
for (int i = 0; i < competitorList.Count; i++)
{
cmd.Parameters["#CompetitorID"].Value = competitorList[i];
cmd.Parameters["#ProductCode"].Value = productCodeList[i];
cmd.Parameters["#ProductName"].Value = productNameList[i];
cmd.Parameters["#Price"].Value = productPriceList[i];
cmd.Parameters["#DateCaptured"].Value = dateCapturedList[i];
int rowsAffected = cmd.ExecuteNonQuery();
}
Everything works correctly but I cant seem to find a way to correctly convert InnerHtml values to a Decimal type. Is there a way of achieving this?

Depending on your values that come from inner html you can do something like this
using (var con = new SqlConnection(connectionString))
{
con.Open();
using (var cmd = new SqlCommand(#"INSERT INTO OnlineProductsTemp$(CompetitorID, ProductCode, ProductName, DateCaptured)
VALUES(#CompetitorID, #ProductCode, #ProductName, #DateCaptured)", con))
{
cmd.Parameters.Add("#CompetitorID", SqlDbType.Int);
cmd.Parameters.Add("#ProductCode", SqlDbType.VarChar);
cmd.Parameters.Add("#ProductName", SqlDbType.VarChar);
cmd.Parameters.Add("#Price", SqlDbType.Decimal);
cmd.Parameters.Add("#DateCaptured", SqlDbType.DateTime);
for (int i = 0; i < competitorList.Count; i++)
{
cmd.Parameters["#CompetitorID"].Value = competitorList[i];
cmd.Parameters["#ProductCode"].Value = productCodeList[i];
cmd.Parameters["#ProductName"].Value = productNameList[i];
cmd.Parameters["#Price"].Value = productPriceList[i];
cmd.Parameters["#DateCaptured"].Value = dateCapturedList[i];
int rowsAffected = cmd.ExecuteNonQuery(); // also the variable rowsAffected is not visible outside the scope of the for loop
}
}
}
Update:
You should, then, convert the values prior to adding them in the list, like so:
foreach (var prices in priceTags)
{
label9.Visible = true;
label9.Text += prices.InnerHtml + "\n";
productPriceList.Add(Decimal.Parse(prices.InnerHtml, <cultureInfoHere>));
label2.Visible = false;
label3.Visible = false;
}
By doing this you don't have to change the list type.

Related

Saving Data entered in gridview using c# and sqlserver

I have a form that has a asp.net gridview contained in it, on page load, I disabled some textboxes of the grid using jQuery.
my save method to the database is not working properly. I removed the grid from the "save" method and it works with the 2 textboxes.
protected void saverecords() {
try {
int suc = 0;
conn = new SqlConnection(connString);
conn.Open();
sqltrans = conn.BeginTransaction();
string sqldelete = "delete from TrainEmpha where TrainCode = '" + txtcode.Text.ToString().Trim() + "'";
SqlCommand comm = new SqlCommand(sqldelete, conn, sqltrans);
comm.ExecuteNonQuery();
comm.Dispose();
string insertgroup = " Insert into TrainEmpha (TrainCode, TrainDesc,disreglev,EmphaLevel,Award1,Award2,Award3,Award4)" +
" Values (#TrainCode, #TrainDesc,#disreglev,#EmphaLevel,#Award1,#Award2,#Award3,#Award4)";
foreach(GridViewRow gvr in gridview.Rows) {
string drplevel = ((DropDownList) gvr.FindControl("drp_grid_lvl")).Text.Trim();
string txttrain = ((TextBox) gvr.FindControl("txttrained")).Text.Trim();
string txtaward_1 = ((TextBox) gvr.FindControl("txtaward1")).Text.Trim();
string txtaward_2 = ((TextBox) gvr.FindControl("txtaward2")).Text.Trim();
string txtaward_3 = ((TextBox) gvr.FindControl("txtaward3")).Text.Trim();
string txtaward_4 = ((TextBox) gvr.FindControl("txtaward4")).Text.Trim();
comm = new SqlCommand(insertgroup, conn, sqltrans);
comm.Parameters.Add("#TrainCode", SqlDbType.VarChar);
comm.Parameters["#TrainCode"].Value = txtcode.Text.Trim();
comm.Parameters.Add("#TrainDesc", SqlDbType.VarChar);
comm.Parameters["#TrainDesc"].Value = txtdescrip.Text.Trim();
comm.Parameters.Add("#disreglev", SqlDbType.VarChar);
comm.Parameters["#disreglev"].Value = drplevel.Trim();
comm.Parameters.Add("#EmphaLevel", SqlDbType.VarChar);
comm.Parameters["#EmphaLevel"].Value = txttrain.Trim();
comm.Parameters.Add("#Award1", SqlDbType.VarChar);
comm.Parameters["#Award1"].Value = txtaward_1.Trim();
comm.Parameters.Add("#Award2", SqlDbType.VarChar);
comm.Parameters["#Award2"].Value = txtaward_2.Trim();
comm.Parameters.Add("#Award3", SqlDbType.VarChar);
comm.Parameters["#Award3"].Value = txtaward_3.Trim();
comm.Parameters.Add("#Award4", SqlDbType.VarChar);
comm.Parameters["#Award4"].Value = txtaward_4.Trim();
suc += comm.ExecuteNonQuery();
comm.Dispose();
}
if (suc > 0) {
ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "Notify", "alert(' RECORDS SAVED SUCCESSFULLY!');", true);
sqltrans.Commit();
} else {
lblDisplayErr.Text = "COULD NOT SAVE";
}

I cant insert data into my DB

I'm trying to insert data into my DB and when i press the button it should get done but it won't
I guess it's from my last layer somewhere in my Query
here's my code
public void InsertInventory(DateTime _date, int _customer_Id,
int _employee_Id, List<int> _product_Id,
List<int> _amountSold,
List<int> _unitPrice, List<int> _totalPrice)
{
Connection_String = #"Data Source=MOSTAFA-PC;Initial Catalog="
+ "Sales and Inventory System"
+ ";Integrated Security=TrueData Source=MOSTAFA-PC;Initial Catalog="
+ "Sales and Inventory System"
+ ";Integrated Security=True;";
Query = "insert into Inventory" +
"(Customer_Id,Employee_Id,Product_Id,[Date],[Amount Sold],[Unit Price],[Total Price])" +
"values (#customer_id,#Employee_id,#Product_id,#[Date],#[Amount_Sold],#[Unit_Price],#[Total_Price])";
using (Con = new SqlConnection(Connection_String))
using (Cmd = new SqlCommand(Query, Con))
{
Cmd.Parameters.Add("#customer_id", SqlDbType.Int);
Cmd.Parameters.Add("#Employee_id", SqlDbType.Int);
Cmd.Parameters.Add("#Product_id", SqlDbType.Int);
Cmd.Parameters.Add("#[Date]", SqlDbType.NVarChar);
//Cmd.Parameters.Add("#[Date]", SqlDbType.Date);
Cmd.Parameters.Add("#[Amount_sold]", SqlDbType.Int);
Cmd.Parameters.Add("#[Unit_Price]", SqlDbType.Decimal);
Cmd.Parameters.Add("#Total_Price", SqlDbType.Decimal);
Cmd.Connection = Con;
Con.Open();
int RecordToAdd = _product_Id.Count;
for (int i = 0; i < RecordToAdd; i++)
{
Cmd.Parameters["#customer_id"].Value = _customer_Id;
Cmd.Parameters["#Employee_id"].Value = _employee_Id;
Cmd.Parameters["#Product_id"].Value = _product_Id;
Cmd.Parameters["#Date"].Value = _date;
Cmd.Parameters["#Amount_sold"].Value = _amountSold;
Cmd.Parameters["#Unit_Price"].Value = _unitPrice;
Cmd.Parameters["#Total_Price"].Value = _totalPrice;
Cmd.ExecuteNonQuery();
}
}
}
I can't figure it out where my problem is
The problem is caused by the values that you set for your parameters.
You should use the indexer to retrieve an element from the lists not the whole lists
// These doesn't change inside the loop, so set it once for all...
Cmd.Parameters["#customer_id"].Value = _customer_Id;
Cmd.Parameters["#Employee_id"].Value = _employee_Id;
Cmd.Parameters["#Date"].Value = _date;
for (int i = 0; i < RecordToAdd; i++)
{
Cmd.Parameters["#Product_id"].Value = _product_Id[i];
Cmd.Parameters["#Amount_sold"].Value = _amountSold[i];
Cmd.Parameters["#Unit_Price"].Value = _unitPrice[i];
Cmd.Parameters["#Total_Price"].Value = _totalPrice[i];
Cmd.ExecuteNonQuery();
}

Failed trying to insert my data

I'm trying to insert some list into my Data base(Microsoft) but i got this run time error
Failed to convert parameter value from a List`1 to a Int32.
here's my code
public void InsertInventory(DateTime _date, int _customer_Id,
int _employee_Id, List<int> _product_Id,
List<int> _amountSold,
List<int> _unitPrice, List<int> _totalPrice)
{
Connection_String = #"Data Source=MOSTAFA-PC;Initial Catalog="
+ "Sales and Inventory System"
+ ";Integrated Security=TrueData Source=MOSTAFA-PC;Initial Catalog="
+ "Sales and Inventory System"
+ ";Integrated Security=True;";
Query = "insert into Inventory" +
"(Customer_Id,Employee_Id,Product_Id,[Date],[Amount Sold],[Unit Price],[Total Price])" +
"values (#customer_id,#Employee_id,#Product_id,#[Date],#[Amount_Sold],#[Unit_Price],#[Total_Price])";
using (Con = new SqlConnection(Connection_String))
using (Cmd = new SqlCommand(Query, Con))
{
Cmd.Parameters.Add("#customer_id", SqlDbType.Int);
Cmd.Parameters.Add("#Employee_id", SqlDbType.Int);
Cmd.Parameters.Add("#Product_id", SqlDbType.Int);
//Cmd.Parameters.Add("#[Date]", SqlDbType.NVarChar);
Cmd.Parameters.Add("#[Date]", SqlDbType.Date);
Cmd.Parameters.Add("#[Amount_sold]", SqlDbType.Int);
Cmd.Parameters.Add("#[Unit_Price]", SqlDbType.Decimal);
Cmd.Parameters.Add("#Total_Price", SqlDbType.Decimal);
Cmd.Connection = Con;
Con.Open();
int RecordToAdd = _product_Id.Count;
for (int i = 0; i < RecordToAdd; i++)
{
Cmd.Parameters["#customer_id"].Value = _customer_Id;
Cmd.Parameters["#Employee_id"].Value = _employee_Id;
Cmd.Parameters["#Product_id"].Value = _product_Id;
Cmd.Parameters["#[Date]"].Value = _date;
Cmd.Parameters["#[Amount_sold]"].Value = _amountSold;
Cmd.Parameters["#[Unit_Price]"].Value = _unitPrice;
Cmd.Parameters["#Total_Price"].Value = _totalPrice;
Cmd.ExecuteNonQuery();
}
i searched the web sites but i couldn't find any thing usefull or similar to my problem
What should i do?
change this:
int RecordToAdd = _product_Id.Count;
for (int i = 0; i < RecordToAdd; i++)
{
Cmd.Parameters["#customer_id"].Value = _customer_Id;
Cmd.Parameters["#Employee_id"].Value = _employee_Id;
Cmd.Parameters["#Product_id"].Value = _product_Id;
Cmd.Parameters["#[Date]"].Value = _date;
Cmd.Parameters["#[Amount_sold]"].Value = _amountSold;
Cmd.Parameters["#[Unit_Price]"].Value = _unitPrice;
Cmd.Parameters["#Total_Price"].Value = _totalPrice;
Cmd.ExecuteNonQuery();
}
To this:
int RecordToAdd = _product_Id.Count;
for (int i = 0; i < RecordToAdd; i++)
{
Cmd.Parameters["#customer_id"].Value = _customer_Id;
Cmd.Parameters["#Employee_id"].Value = _employee_Id;
Cmd.Parameters["#Product_id"].Value = _product_Id[i];
Cmd.Parameters["#[Date]"].Value = _date;
Cmd.Parameters["#[Amount_sold]"].Value = _amountSold[i];
Cmd.Parameters["#[Unit_Price]"].Value = _unitPrice[i];
Cmd.Parameters["#Total_Price"].Value = _totalPrice[i];
Cmd.ExecuteNonQuery();
}
Notice in the second block I'm using the iterator of the loop to index which item in the list I'm inserting each time.
EDIT: Also, that connection_string you built doesn't look right. You might want to review it and correct any mistakes
Change the "List<>" in FUNCTION PARAMETERS for Int32 or Integer.

How to update and delete data without a few words from text file

My database tables includes columns like that id,name,surname,phone,address,date. Id is automatically increasing.
name=joe|surname=clark|phone=23132131|address=jdsakldjakldja|date=11.02.2015 14:30:45
name=betty|surname=ugly|phone=32112121|address=dsadaewqeqrsa|date=11.02.2015 14:30:45
This is my INSERT codes
string connStr = #"Data Source=ANLZ\SQLEXPRESS;Initial Catalog=testdb; Trusted_Connection=True;";
string createQuery = "INSERT INTO tbl_test(name,surname,phone,address,date) VALUES(#name,#surname,#phone,#address,#date)";
SqlConnection conn;
SqlCommand cmd;
string[] importfiles = Directory.GetFiles(#"C:\Users\An\Desktop\", "test.txt");
using (conn)
{
using (cmd = new SqlCommand(createQuery, conn))
{
cmd.Parameters.Add("#name", SqlDbType.NVarChar, 50);
cmd.Parameters.Add("#surname", SqlDbType.NVarChar, 50);
cmd.Parameters.Add("#phone", SqlDbType.NVarChar, 50);
cmd.Parameters.Add("#address", SqlDbType.NVarChar, 200);
cmd.Parameters.Add("#date", SqlDbType.DateTime);
foreach (string importfile in importfiles)
{
string[] allLines = File.ReadAllLines(importfile);
baglanti.Open();
for (int index = 0; index < allLines.Length; index++)
{
string[] items = allLines[index].Split(new[] { '|' })
.Select(i => i
.Split(new[] { '=' })[1])
cmd.Parameters["#name"].Value = items[0];
cmd.Parameters["#surname"].Value = items[1];
cmd.Parameters["#phone"].Value = items[2];
cmd.Parameters["#address"].Value = items[3];
cmd.Parameters["#date"].Value = items[4];
cmd.ExecuteNonQuery();
}
conn.Close();
}
}
}
I would like to update and delete certain text to my database. Also i don't need to save same records with same id. How can i do it?
The ID of any Table should have AUTO_INCREMENT and be of BIGINT or INT type, and code never set the ID, the SQL Server does that.
To update you would make a new SQLCommand of and update type.
string connStr = #"Data Source=ANLZ\SQLEXPRESS;Initial Catalog=testdb; Trusted_Connection=True;";
int updateId = int.Parse(formTextBox.Text); //Or where ever you set the ID to when it is pulled from the database.
string updateCommand = "UPDATE tbl_test SET [surname]=#surname WHERE ID = #id";
using (OleDbConnection conn = new OleDbConnection(connStr))
{
using (OleDbCommand comm = new OleDbCommand())
{
comm.Connection = conn;
comm.CommandText = updateCommand;
comm.CommandType = CommandType.Text
comm.Parameters.AddWithValue("#surname", items[1])
comm.Parameters.AddWithValue("#id",updateId);
try
{
comm.Open();
conn.ExecuteNonQuery();
}
catch(OleDbException ex)
{
//Do some error catching Messagebox/Email/Database entry 'Or Nothing'
}
}
}
Deleting is Much easier
string connStr = #"Data Source=ANLZ\SQLEXPRESS;Initial Catalog=testdb; Trusted_Connection=True;";
int updateId = int.Parse(formTextBox.Text); //Or where ever you set the ID to when it is pulled from the database.
string deleteComand = "Delete FROM tbl_test WHERE ID = #id";
using (OleDbConnection conn = new OleDbConnection(connStr))
{
using (OleDbCommand comm = new OleDbCommand())
{
comm.Connection = conn;
comm.Parameters.AddWithValue("#id", updateId);
try
{
comm.Open();
conn.ExecuteNonQuery();
}
catch (OleDbException ex)
{
//Do some error catching Messagebox/Email/Database entry 'Or Nothing'
}
}
}
Couple things to Note - Using statements, and Try Catch Blocks.
Using will Dispose of and Connection or other object that has a Dispose implemented.
Try Catch will grab any errors that come from doing the Database call, unable to connect, or the Row to Update could not be updated.
How i can change that Update codes?
public string updateQuery = "UPDATE tbl_test SET name=#name,surname=#surname,phone=#phone,address=#address,date=#date WHERE id=#id ";
// ...
conn = new SqlConnection(connStr);
try
{
string[] importfiles = Directory.GetFiles(#"C:\Users\An\Desktop\", "test.txt");
using (conn)
{
using (cmd = new SqlCommand(updateQuery, conn))
{
cmd.Parameters.Add("#name", SqlDbType.NVarChar, 50);
cmd.Parameters.Add("#surname", SqlDbType.NVarChar, 50);
cmd.Parameters.Add("#phone", SqlDbType.NVarChar, 50);
cmd.Parameters.Add("#address", SqlDbType.NVarChar, 200);
cmd.Parameters.Add("#date", SqlDbType.DateTime);
cmd.Parameters.Add("#id", SqlDbType.Int);
foreach (string importfile in importfiles)
{
string[] allLines = File.ReadAllLines(importfile);
conn.Open();
for (int index = 0; index < allLines.Length; index++)
{
string[] items = allLines[index].Split(new[] { '|' })
.Select(i => i
.Split(new[] { '=' })[1])
.ToArray();
cmd.Parameters["#name"].Value = items[0];
cmd.Parameters["#surname"].Value = items[1];
cmd.Parameters["#phone"].Value = items[2];
cmd.Parameters["#address"].Value = items[3];
cmd.Parameters["#date"].Value = items[4];
cmd.ExecuteNonQuery();
}
conn.Close();
}
}
}
}
This is for delete
public string deleteQuery = "DELETE FROM tbl_test WHERE id=#id";
// ...
conn = new SqlConnection(connStr);
try
{
string[] importfiles = Directory.GetFiles(#"C:\Users\An\Desktop\", "test.txt");
using (conn)
{
using (cmd = new SqlCommand(deleteQuery, baglanti))
{
cmd.Parameters.Add("#id", SqlDbType.Int);
foreach (string importfile in importfiles)
{
string[] allLines = File.ReadAllLines(importfile);
conn.Open();
for (int index = 0; index < allLines.Length; index++)
{
string[] items = allLines[index].Split(new[] { '|' })
.Select(i => i
.Split(new[] { '=' })[1])
.ToArray();
cmd.Parameters["#name"].Value = items[0];
cmd.Parameters["#surname"].Value = items[1];
cmd.Parameters["#phone"].Value = items[2];
cmd.Parameters["#address"].Value = items[3];
cmd.Parameters["#date"].Value = items[4];
cmd.ExecuteNonQuery();
}
conn.Close();
}
}
}
}
For Select it is a little more involved.
**public string selectQuery= "Select * FROM tbl_test" ;
conn = new SqlConnection(connStr);
try
{
using (conn)
{
using (cmd = new SqlCommand(selectQuery, conn))
{
using(var dataReader = cmd.ExecuteReader())
{
while(datareader.reader())
{
//Read the datareader for values and set them .
var id = datareader.GetInt32(0);
}
}
}
}
}**

Index was outside the bounds of the array in c#

I want to insert MySqlDataReader read value into an array.but I get the exception "Index was outside the bounds of the array". Here is my code,
string[] a = new string[1000];
string myconstring = "SERVER=localhost;" + "DATABASE=alicosms;" + "UID=root;" + "PASSWORD=;";
MySqlConnection mycon = new MySqlConnection(myconstring);
string sql = "SELECT flag FROM sms_data_bankasia group by flag";
MySqlCommand comd = mycon.CreateCommand();
comd.CommandText = sql;
mycon.Open();
MySqlDataReader dtr = comd.ExecuteReader();
count = 0;
int i = 0;
while (dtr.Read())
{
a[i] = dtr.GetValue(i).ToString();
i++;
}
What can I do.Any one can help me?
Try cleaning your code a little and use a dynamically resizing List<T> to which you can add elements:
var result = new List<string>();
var myconstring = "SERVER=localhost;DATABASE=alicosms;UID=root;PASSWORD=;";
using (var con = new MySqlConnection(myconstring))
using (var cmd = con.CreateCommand())
{
con.Open();
cmd.CommandText = "SELECT flag FROM sms_data_bankasia group by flag";
using (var reader = cmd.ExecuteReader())
{
while (reader.Read())
{
result.Add(reader.GetString(reader.GetOrdinal("flag")));
}
}
}
string[] a = result.ToArray();
This looks suspicious to me:
a[i] = dtr.GetValue(i).ToString();
That means you're fetching column 0 of row 0, column 1 of row 1, column 2 of row 2 etc... but you've only got a single column ("flag").
I suspect you meant:
a[i] = dtr.GetValue(0).ToString();
That will still fail if there are more than 1000 rows though - it would be better to use a List<string>:
List<string> data = new List<string>();
while (dtr.Read())
{
data.Add(dtr.GetValue(0).ToString()); // Or call GetString
}

Categories