c# integer data load to text box by selecting dropdownlist - c#

i have tried to load the integer value to textbox from db by selecting the dropdownlist item. I didn't get any error, but the value was not display in the text box. this is the code what i have written, please correct me,
public void SiteNo()
{
Conhr.Open();
//int anInteger;
//anInteger = Convert.ToInt32(TextBox1.Text);
//anInteger = int.Parse(TextBox1.Text);
string sq = "select SiteCode from tbl_SiteMaster where Sitealiasname='" + ddlsite.SelectedItem.Text + "' ";
SqlCommand d = new SqlCommand(sq, Conhr);
SqlDataReader r;
r = d.ExecuteReader();
while (r.Read())
{
TextBox1.Text = r.GetValue(0).ToString();
}
r.close();
Conhr.Close();
}

//change code to this to find the problem
public void SiteNo()
{
Conhr.Open();
//int anInteger;
//anInteger = Convert.ToInt32(TextBox1.Text);
//anInteger = int.Parse(TextBox1.Text);
string sq = "select count(SiteCode) from tbl_SiteMaster where Sitealiasname='" + ddlsite.SelectedItem.Text + "' ";
SqlCommand d = new SqlCommand(sq, Conhr);
SqlDataReader r;
r = d.ExecuteReader();
while (r.Read())
{
TextBox1.Text = r.GetValue(0).ToString();
}
r.close();
Conhr.Close();
}

Related

How to add Get.Attribute(src) values into List<string> or am i add values to other list method c#?

I am coding with C# selenium. I need your help. I can find an attribute src and can write it. But I need to add these values to an existing List, because I will use it for adding these values to the database. But when I run the provided code, it never updated the List, so it is always empty.
// FIND ELEMENT WHICH WILL BE USE FOR GET.ATTRIBUTE(SRC)
IReadOnlyCollection<IWebElement> imageelements = driver.FindElements(By.CssSelector("div.product-slide"));
List<IWebElement> elements = new List<IWebElement>(imageelements) ;
int a = elements.Count;
string b = Convert.ToString(a);
label5.Text = b;
// LIST FOR STORE THE GET.ATTRIBUTE VALUES
List<string> srclist = new List<string>();
int c = srclist.Count;
int i = 1;
foreach (IWebElement element in elements)
{
// GET ATRRIBUTE(SRC) OF ELEMENT
var imagetag = element.FindElement (By.TagName("img"));
string imagesrc = imagetag.GetAttribute("src");
Thread.Sleep(1000);
// ADDING VALUES TO LIST ------- IT IS MY PROBLEM: VALUES NOT ADDING TO LIST
srclist.Add(imagesrc);
label6.Text = "src " + imagesrc + " " + c;
Thread.Sleep(1000);
label5.Text = "src islenir" + i;
i++;
if (a == i) break;
}
label6.Text = ">>>>>" + c;
EDIT
string currenturl = driver.Url;
// item Name
var itemName = driver.FindElement(By.CssSelector(".pr-new-br")).Text;
// item Price
var itemPrice = driver.FindElement(By.ClassName("prc-dsc")).Text;
label2.Text = itemName + itemPrice;
// FIND ELEMENT WHICH WILL BE USE FOR GET.ATTRIBUTE(SRC)
IReadOnlyCollection<IWebElement> imageelements = driver.FindElements(By.CssSelector("div.product-slide"));
List<IWebElement> elements = new List<IWebElement>(imageelements) ;
int a = elements.Count;
string b = Convert.ToString(a);
label5.Text = b;
// LIST FOR STORE THE GET.ATTRIBUTE VALUES
List<string> srclist = new List<string>();
int c = srclist.Count;
int i = 1;
foreach (IWebElement element in elements)
{
// GET ATRRIBUTE(SRC) OF ELEMENT
var imagetag = element.FindElement (By.TagName("img"));
string imagesrc = imagetag.GetAttribute("src");
Thread.Sleep(1000);
// ADDING VALUES TO LIST ------- IT IS MY PROBLEM: VALUES NOT ADDING TO LIST
srclist.Add(imagesrc);
label6.Text = "src " + imagesrc + " " + c;
Thread.Sleep(1000);
label5.Text = "src islenir" + i;
i++;
if (a == i) break;
}
int gg = srclist.Count;
label6.Text = ">>>>>" + gg;
string combinsrc = string.Join(",", srclist.ToArray());
string connetionstring = #"Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=D:\vsss\veri\veri\excel\veridatabase.mdf;Integrated Security=True";
con = new SqlConnection(connetionstring);
cmd = new SqlCommand();
cmd.Connection = con;
// INSERT INTO DATABASE === ALL CORRECTLY INSERTING JUST ---COMBINSRC--- VALUES NOT INSERT
cmd.CommandText = "INSERT INTO urun (ismi, fiyati, link, hiperlink ) VALUES ('" + itemName + "','" + itemPrice + "','" + currenturl + "','" + combinsrc + "')";
label5.Text = "src alindi";
Thread.Sleep(2000);
con.Open();
cmd.ExecuteNonQuery();
As I could understand your problem, you think that the srclist is never updated, because your variable c is always 0. This is the supposed behavoiur, because you set its value by counting elements in the empty (just created) List and never update it.
The solution is easy, so you just can add the following code line after the srclist.Add(imagesrc);:
c = srclist.Count;
This is not the best practice, but it should help you.

Visual Studio Database Not Updating

I am working on a school project and for some reason my mysql database doesn't update despite no of row changed is more than 0 and triggering the Update sucessful alert. It also manage to only update my image data from my fileupload.
**admin_products_details_edit.aspx.cs**
protected void btn_ProdEdit_Click(object sender, EventArgs e)
{
int result = 0;
string image = "";
if (FileUpload_ProdImg.HasFile == true)
{
image = "images\\" + FileUpload_ProdImg.FileName;
img_result.ImageUrl = FileUpload_ProdImg.FileName;
}
else
{
image = img_result.ImageUrl;
}
Product Prod = new Product();
string datProdID = lbl_ProdID.Text;
string datProdName = tb_ProdName.Text;
string datProdDesc = tb_ProdDesc.Text;
string datProdImg = img_result.ImageUrl;
decimal datProdPrice = decimal.Parse(tb_ProdPrice.Text);
int datProdCal = int.Parse(tb_ProdCal.Text);
int datStockLvl = int.Parse(tb_StockLvl.Text);
result = Prod.ProductUpdate(datProdID, datProdName, datProdDesc, datProdImg, datProdPrice, datProdCal, datStockLvl);
if (result > 0)
{
string saveimg = Server.MapPath(" ") + "\\" + image;
FileUpload_ProdImg.SaveAs(saveimg);
Response.Write("<script>alert('Update successful');</script>");
Response.Redirect("admin_products_details.aspx?ProdID=" + datProdID);
}
else
{
Response.Write("<script>alert('Update fail');</script>");
}
}<-The code for the button edit event trigger
**Product.cs**
...public int ProductUpdate(string upID, string upName, string upDesc, string upImg, decimal upPrice, int upCal, int upstkLvl)
{
string queryStr = "UPDATE Products SET" + " ProdName = #productName, " + " ProdDesc = #productDesc, " + " ProdImg = #productImage, " + " ProdPrice = #productPrice, " + " ProdCalorie = #productCal, " + " StockLevel = #productStkLvl " + " WHERE ProdID = #productID";
SqlConnection conn = new SqlConnection(_connStr);
SqlCommand cmd = new SqlCommand(queryStr, conn);
cmd.Parameters.AddWithValue("#productID", upID);
cmd.Parameters.AddWithValue("#productName", upName);
cmd.Parameters.AddWithValue("#productDesc", upDesc);
cmd.Parameters.AddWithValue("#productImage", upImg);
cmd.Parameters.AddWithValue("#productPrice", upPrice);
cmd.Parameters.AddWithValue("#productCal", upCal);
cmd.Parameters.AddWithValue("#productStkLvl", upstkLvl);
conn.Open();
int nofRow = 0;
nofRow = cmd.ExecuteNonQuery();
conn.Close();
return nofRow;
}<-The code for updating the mysql database,located in a different cs file,titled Product.cs
My mysql database table is called Products
Thank you very much for your help in advance.

How to set datagridview scroll position in C# winform when enter key is used in keydown event?

I'm having problem setting the vertical scroll position. I have followed this similar question and I get the expected result for CellDoubleClick Event. But for KeyDown Event, where the user will press Enter key, it resets the vertical scroll position at the top
These are my CellDouble Click and KeyDown events.
private void dataGridSrch_KeyDown(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.Enter)
{
addToSell();
}
}
private void dataGridSrch_CellDoubleClick(object sender, DataGridViewCellEventArgs e)
{
addToSell();
}
This is my addToSell function, this function will call after that will update the DataGridView.
public void addToSell()
{
if (dataGridSrch.SelectedRows.Count > 0)
{
DataRow row = (dataGridSrch.SelectedRows[0].DataBoundItem as DataRowView).Row;
if (Convert.ToInt32(row["Stock"].ToString()) > 0)
{
string sellProd = row["Brand"].ToString() + " " + row["Part No."].ToString();
int sellQty = Convert.ToInt32(numSell.Value);
string sellUnit = row["Unit"].ToString();
double sellPrice = double.Parse(row["Price"].ToString()) * sellQty;
double sPrice = double.Parse(row["Price"].ToString());
dataGridSales.Rows.Add(sellProd, sellQty, sellUnit, sellPrice, sPrice, row["Part No."].ToString(), row["Stock"].ToString());
int count = 0;
double total = 0;
for (int i = 0; i < dataGridSales.Rows.Count; i++)
{
total += Convert.ToDouble(dataGridSales.Rows[i].Cells[3].Value);
count += Convert.ToInt32(dataGridSales.Rows[i].Cells[1].Value);
}
lblTotAmt.Text = "Total Amount: " + total.ToString("C2");
lblTotItem.Text = "Total Items: " + count;
amount = total;
{
conn.Open();
using (SqlCommand cmd = new SqlCommand(#"UPDATE [dbo].[products]
SET Stock = Stock - '" + sellQty + "' WHERE [Part No.] = '" + row["Part No."] + "'", conn))
{
cmd.ExecuteNonQuery();
}
conn.Close();
}
>>>>>>>>>>>>>>>>after(); //THIS IS WHERE AFTER FUNCTION IS CALLED
}
else
{
MessageBox.Show("You dont have any stock for the selected item, please restock immediately.", "Please restock", MessageBoxButtons.OK);
}
}
if (dataGridSales.Rows.Count > 0)
{
cmbMOP.Enabled = true;
}
}
And this is my after function.
public void after()
{
string item = cmbItem.Text;
string brand = cmbBrand.Text;
string part = txtPart.Text;
string manu = cmbMan.Text;
string car = cmbCar.Text;
string year = cmbYr.Text;
conn.Open();
{
int index = dataGridSrch.SelectedRows[0].Index;
>>>>>>>>>>>>int scrollPos = dataGridSrch.FirstDisplayedScrollingRowIndex; //GET THE SCROLL POSITION
string sel = #"SELECT * FROM[dbo].[products] WHERE 1=1";
using (SqlCommand cmd = new SqlCommand())
{
if (!string.IsNullOrEmpty(item))
{
sel += " AND Item = #Item";
cmd.Parameters.Add("#Item", SqlDbType.VarChar).Value = item;
}
if (!string.IsNullOrEmpty(brand))
{
sel += " AND Brand = #Brand";
cmd.Parameters.Add("#Brand", SqlDbType.VarChar).Value = brand;
}
if (!string.IsNullOrEmpty(part))
{
sel += " AND [Part No.] = #Part";
cmd.Parameters.Add("#Part", SqlDbType.VarChar).Value = part;
}
if (!string.IsNullOrEmpty(manu))
{
sel += " AND Manufacturer = #Manufacturer";
cmd.Parameters.Add("#Manufacturer", SqlDbType.VarChar).Value = manu;
}
if (!string.IsNullOrEmpty(car))
{
sel += " AND Car = #Car";
cmd.Parameters.Add("#Car", SqlDbType.VarChar).Value = car;
}
if (!string.IsNullOrEmpty(year))
{
sel += " AND Year = #Year";
cmd.Parameters.Add("#Year", SqlDbType.VarChar).Value = year;
}
cmd.CommandText = sel;
cmd.Connection = conn;
using (SqlDataAdapter sda = new SqlDataAdapter(cmd))
{
DataTable dt = new DataTable();
DataView dv = dt.DefaultView;
sda.Fill(dt);
dataGridSrch.DataSource = dt;
dv.Sort = "Item, Brand, Manufacturer, Car, Year, Price ASC ";
dataGridSrch.Columns["Price"].DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleRight;
dataGridSrch.Columns["Price"].DefaultCellStyle.Format = "C2";
dataGridSrch.Columns["Stock"].DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleRight;
dataGridSrch.Rows[index].Selected = true;
>>>>>>>>>>>>>>>>>>>>dataGridSrch.FirstDisplayedScrollingRowIndex = scrollPos; //AFTER UPDATE SET THE SCROLL POSITION
typeof(DataGridView).InvokeMember("DoubleBuffered", BindingFlags.NonPublic |
BindingFlags.Instance | BindingFlags.SetProperty, null,
dataGridSrch, new object[] { true });
}
}
}
conn.Close();
}
I have also change my KeyDown Event to this
private void dataGridSrch_KeyDown(object sender, KeyEventArgs e)
{
int index = dataGridSrch.SelectedRows[0].Index;
int scrollPos = dataGridSrch.FirstDisplayedScrollingRowIndex;
if (e.KeyCode == Keys.Enter)
{
addToSell();
dataGridSrch.Rows[index].Selected = true;
dataGridSrch.FirstDisplayedScrollingRowIndex = scrollPos;
}
}
But still it resets the scroll position.

"OleDBException was unhandled. Data type mismatch in criteria expression." in AutoNumber (id). What to do?

I have this codes below, but I don't know what is the reason why it was always having errors. Here is the code:
private void btn_acart_Click(object sender, EventArgs e)
{
con.Open();
string[] product = new string[7];
string[] select = new string[2];
int[] num = new int[5];
foreach (ListViewItem item in listView1.SelectedItems)
{
select[1] = item.Text;
string str = "SELECT * FROM [lblProduct] WHERE [prod_id]='"+select[1]+"'";
com = new OleDbCommand(str, con);
read = com.ExecuteReader();
while (read.Read())
{
product[1] = (read["prod_id"].ToString());
product[2] = (read["prod_name"].ToString());
product[3] = (read["prod_price"].ToString());
product[4] = (read["prod_stock"].ToString());
this.listView2.Items.Add(new ListViewItem(new string[] { product[1], product[2], product[3], product[4] }));
cartitems++;
num[1] = int.Parse(product[4]);
num[2] = int.Parse(txt_items.Text);
string strg = "UPDATE lblProduct SET prod_stock='"+(num[1] - num[2]+"' WHERE prod_id='"+product[1]+"'");
com = new OleDbCommand(strg, con);
com.ExecuteNonQuery();
}
}
loaddbase();
con.Close();
txt_items.Text = "0";
}
}
What should I do? What should I change? Please help! The error is always repeating at the read = com.ExecuteReader();
Access Database:
Format: (Field Name - Data Type)
prod_id - AutoNumber
prod_name - Text
prod_price - Text
prod_stock - Text
Are there anything to change in the database?

Wrong date format C#, Oracle

I'm trying to get my date in the correct format(dd/mm/yyyy). At the moment its in this format: MM-DD-YYYY HH24:MI:SS When I change it to dd/mm/yyyy, it works in the database(Oracle). As soon as I run it in my app I get exception: IndexOutOfRange at :
this.InfoList9.Add(dr["start_rcv_datetime"].ToString());
Please see my code below.
public List<String> InfoList = new List<String>();
private void populatelblDate()
{
conn.Open();
string query;
query = "select to_char(dg.start_rcv_datetime,'dd/mm/yyyy') from dc_pallet dp, dc_pallet_stock dps , dc_grv dg , sku s ,prod_size ps,colour c ,purch_order_carton_sku pocs , dc_crane_instruc dci where dps.pallet_id_no = '" + palletId.ToString() + "' and dp.pallet_id_no = dps.pallet_id_no and dg.dc_grv_id_no = dps.dc_grv_id_no and dg.order_no = dps.order_no and dg.company_id_no = dps.company_id_no and s.company_id_no = dps.company_id_no and s.company_id_no = dg.company_id_no and dps.company_id_no = c.company_id_no and dps.company_id_no = ps.company_id_no and s.prod_size_id_no = ps.prod_size_id_no and s.colour_id_no = c.colour_id_no and dps.company_id_no = ps.company_id_no and pocs.order_no = dps.order_no and pocs.carton_code = dps.carton_code and pocs.company_id_no = dps.company_id_no and pocs.sku_id_no = s.sku_id_no and dci.pallet_id_no(+) = dp.pallet_id_no";
OracleCommand cmd = new OracleCommand(query, conn);
OracleDataReader dr = cmd.ExecuteReader();
while (dr.Read())
{
this.InfoList.Add(dr["start_rcv_datetime"].ToString());
}
dr.Close();
conn.Close();
}
private void frmInfo_Load(object sender, EventArgs e)
{
populatelblDate();
lbl1.Text = this.InfoList[0];
}
Then I have a prev and next button as well...
Your IndexOutOfRange exception suggests that the immediate problem is that the result set doesn't contain a column of start_rcv_datetime - presumably because of the to_char conversion.
Don't deal with strings at the database side at all. Fetch the value as a DateTime, and then format it at the client in whatever you want to.
Use dr.GetDateTime to fetch the value, having removed the to_char part from your query:
query = "select dg.start_rcv_datetime from ...";
using (OracleCommand cmd = new OracleCommand(query, conn))
{
using (OracleDataReader dr = cmd.ExecuteReader())
{
int dateColumn = dr.GetOrdinal("start_rcv_datetime");
while (dr.Read())
{
DateTime date = dr.GetDateTime(0);
// Or whatever - consider cultural implications
string text = date.ToString("dd/MM/yyyy");
InfoList.Add(text);
}
}
}
(Note the using statements - you should always make sure you clean up your database-related resources.)
Your first column doesn't have a name andso you cannot retrieve it with "start_rcv_datetime"
The immediate solution would be to change the sql to read
query = "select to_char(dg.start_rcv_datetime,'dd/mm/yyyy') as start_rcv_datetime from dc_pallet dp, dc_pallet_stock dps , dc_grv dg , sku s ,prod_size ps,colour c ,purch_order_carton_sku pocs , dc_crane_instruc dci where dps.pallet_id_no = '" + palletId.ToString() + "' and dp.pallet_id_no = dps.pallet_id_no and dg.dc_grv_id_no = dps.dc_grv_id_no and dg.order_no = dps.order_no and dg.company_id_no = dps.company_id_no and s.company_id_no = dps.company_id_no and s.company_id_no = dg.company_id_no and dps.company_id_no = c.company_id_no and dps.company_id_no = ps.company_id_no and s.prod_size_id_no = ps.prod_size_id_no and s.colour_id_no = c.colour_id_no and dps.company_id_no = ps.company_id_no and pocs.order_no = dps.order_no and pocs.carton_code = dps.carton_code and pocs.company_id_no = dps.company_id_no and pocs.sku_id_no = s.sku_id_no and dci.pallet_id_no(+) = dp.pallet_id_no";
However you could simply return the date as a datetime from the database and then use string.Format on the result
eg.
this.InfoList.Add(string.Format("{0:dd/MM/yyyy}", dr["start_rcv_datetime"]));

Categories