I have selected multiple datarows with same product name, price and quantity and sorted them according to their primary key values in datatable. But when I decrease stock quantity, it decreases from all the rows. I want my code to check stock quantity according to user quantity entered in textbox and decrease it from FIRST ROW ONLY. This is what I have been able to do so far. apologies in advance for bad formatting I am new to programming and stackoverflow.
The data table has columns
Item_Name, Item_Quantity, Item_Price.
Code:
private void btn_save_Click(object sender, EventArgs e)
{
SqlCommand cmd = con.CreateCommand();
cmd.CommandType = CommandType.Text;
cmd.CommandText = "select * from stock_recieve where Item_Name like'" + comboBoxitem.Text + "'order by [Bill No] asc";
cmd.ExecuteNonQuery();
DataTable dt = new DataTable();
SqlDataAdapter da = new SqlDataAdapter(cmd);
da.Fill(dt);
foreach (DataRow dr in dt.Rows)
{
// DataRow row = dt.Select("Item_Quantity").FirstOrDefault();
dt.Rows[0]["Item_Quantity"]=;
int qty = 0;
string pname = "";
qty = Convert.ToInt32(dr["Item_Quantity"].ToString());
qty = Convert.ToInt32(textBoxqty.Text);
pname = dr["Item_Name"].ToString();
SqlCommand cmd6 = con.CreateCommand();
cmd6.CommandType = CommandType.Text;
cmd6.CommandText = "update stock_recieve set Item_Quantity=Item_Quantity-" + qty + "where Item_Name ='" + pname.ToString() + "'";
cmd6.ExecuteNonQuery();
}
//MessageBox.Show("Record inserted successfully");
}
Just use top 1 on your select query . Also using SQL parameters is very important. Try like:
...
cmd.CommandText = "select TOP 1 * from stock_recieve where Item_Name like #name order by [Bill No] asc";
cmd.Parameters.Add("#name", SqlDbType.NVarChar).Value =comboBoxitem.Text;
cmd.ExecuteNonQuery();
...
Related
The below is my code to insert gridview data into a database. However, using this I want to check and restrict insertion into the database where records have the same name, location, education and salary. If all of these are the same and those already present in database they should not get inserted. If any one column is different then they should get inserted.
protected void btn_insert_Click(object sender, EventArgs e)
{
foreach (GridViewRow g1 in GridView1.Rows)
{
SqlConnection con = new SqlConnection(connStr);
cmd = new SqlCommand("insert command", con);
con.Open();
cmd.ExecuteNonQuery();
con.Close();
}
UploadStatusLabel.Text = "Records Inserted Successfully";
}
I think hitting the database inside a for loop is a very bad idea when you have other options. I'm not tackling this issue in the below sample.
Your code may be subject to SQL Injection, you need to use parameters to pass your values. If someone filled the input with ";DROP TABLE OpenOfficetext;" and they have DROP permissions, it will be a problem if you're just concatenating strings.
To avoid duplicates, you can check first if a similar record exists.
foreach (GridViewRow g1 in GridView1.Rows)
{
string insertCommand = "insert into OpenOfficetext(Name, Location, Education, Salary) values(#p1, #p2, #p3, #p4)";
string selectCommand = "SELECT COUNT(*) FROM OpenOfficetext WHERE Name = #p1 AND Location = #p2 AND Education = #p3 AND Salary = #p4";
SqlConnection con = new SqlConnection(connStr);
SqlCommand cmd = new SqlCommand(selectCommand, con);
con.Open();
cmd.Parameters.AddWithValue("#p1", g1.Cells[0].Text);
cmd.Parameters.AddWithValue("#p2", g1.Cells[1].Text);
cmd.Parameters.AddWithValue("#p3", g1.Cells[2].Text);
cmd.Parameters.AddWithValue("#p4", g1.Cells[3].Text);
if (Convert.ToInt32(cmd.ExecuteScalar()) == 0)
{
cmd.CommandText = insertCommand;
cmd.ExecuteNonQuery();
}
con.Close();
}
please use the below code
if not exist (select * from OpenOfficetext where Name='" + g1.Cells[0].Text + "' and Location='" + g1.Cells[1].Text + "' and Education = '" + g1.Cells[2].Text + "' and Salary = '" + g1.Cells[3].Text + "' )
Begin
SqlConnection con = new SqlConnection(connStr);
cmd = new SqlCommand("insert into OpenOfficetext(Name,Location,Education,Salary) values ('" + g1.Cells[0].Text + "','" + g1.Cells[1].Text + "','" + g1.Cells[2].Text + "','" + g1.Cells[3].Text + "')", con);
con.Open();
cmd.ExecuteNonQuery();
con.Close();
End
I have a form and i have a listbox in it to select multiple values of different dates. but requirement is one date can be booked for 2 users only once 2 users book the date then i just have to remove it from listbox.
I have created 3 tables. One table (table_dates) is just shows the dates in different rows and second table (table_users) is storing users information and third table (table_map) is mapping user with the dates.
How to write a logic to check if selected date is registered by 2 users already?
Please check my c# code below
using (SqlCommand cmd = new SqlCommand())
{
cmd.Connection = conn;
cmd.CommandType = CommandType.Text;
cmd.CommandText = "INSERT INTO table_users(Name,Email) OUTPUT INSERTED.userId Values (#name,#email)";
cmd.Parameters.AddWithValue("#name", name);
cmd.Parameters.AddWithValue("#email", email);
int lastId = (int)cmd.ExecuteScalar();
if (lastVolId > 0)
{
SqlCommand cmd2 = new SqlCommand();
int counter = 0;
string query = "";
foreach (ListItem li in listBox.Items)
{
if (li.Selected)
{
// I need to write some thing here to check if selected date is registered 2 times
query = "INSERT INTO table_map(userId,dateId) VALUES('" + lastId + "','" + li.Value + "')";
cmd2 = new SqlCommand(query, conn);
cmd2.ExecuteNonQuery();
counter++;
}
}
}
else
{
//Error notification
}
}
Does you table_Date has a column for a unique dateID? It is mendatory for operation u want to perform.
What u need to do is Perform a SELECT QUERY to check if it exists twice.
String selectStatent="SELECT * FROM table_Map WHERE dateID = #dateID";
SqlCommand selectCommand = new SqlCommand( selectStatement, connectionString);
int rowCount = selectCommand.ExecuteScalaer();
if( rowCount <= 2)
{
//Proceed
}
Im trying to display user data from database into textbox, so that user can edit/update that data later.
Im getting error of no value has been set for at least one of the required parameters.
I did not write the SELECT * FROM, because i'm not displaying data like AdminRights.
Can you please help me fix the error?
This is my code
private void refresh_Click(object sender, RoutedEventArgs e)
{
if (!isPostBack)
{
DataTable dt = new DataTable();
con.Open();
OleDbDataReader dr = null;
OleDbCommand cmd = new OleDbCommand("SELECT [Name], [LastName], [UserName], [Password], [Address], [Email] FROM User WHERE [ID] = ?", con);
dr = cmd.ExecuteReader();
while (dr.Read())
{
name.Text = (dr["Name"].ToString());
lName.Text = (dr["LastName"].ToString());
uName.Text = (dr["UserName"].ToString());
pass.Text = (dr["Password"].ToString());
address.Text = (dr["Address"].ToString());
email.Text = (dr["Email"].ToString());
id.Text = (dr["ID"].ToString());
}
con.Close();
}
}
.....FROM User WHERE [ID] = ?", con);
The ? placeholder requires a parameter defined in the command parameters collection.
So, before calling ExecuteReader you need to add the parameter for the ID field
cmd.Parameters.AddWithValue("#p1", ????value for the ID field);
dr = cmd.ExecuteReader();
If you want to retrieve a single record from your table you need to know the value for the field that uniquely identifies the records in your table.
To get that value it is necessary to understand how do you reach this code. If you select a row from a list, grid or combo, probably you have loaded that control with your user names and their ID.
String id = idTextBox.Text;
OleDbCommand command = new OleDbCommand("Select *from User Where [ID]= "+ id +" ");
command.Connection = conn;
OleDbDataReader dr = null;
conn.Open();
dr = command.ExecuteReader();
while (dr.Read())
{
name.Text = (dr["Name"].ToString());
lName.Text = (dr["LastName"].ToString());
uName.Text = (dr["UserName"].ToString());
pass.Text = (dr["Password"].ToString());
address.Text = (dr["Address"].ToString());
email.Text = (dr["Email"].ToString());
id.Text = (dr["ID"].ToString());
}
conn.Close();
this will work fine change lines and execute
I have written following code.
my 1st orderid has both records for process 1 and process 2
but my 2nd orderid has record only for process 1.
when i select orderid 2 after selecting orderid 1 it keeps the value as it is for orderid 1 in process 2 textbox.
i want that textbox to be blank
protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)
{
DbConnect objdbc = new DbConnect();
SqlConnection con = objdbc.openConnection();
SqlCommand cmd = new SqlCommand("SELECT [orderid],[processid],[orgid],[processdesc] ,[perwet] FROM [anghan].[dbo].[ProcessOrder] where orderid='" + DropDownList1.SelectedItem.Value + "' and processid=1 ", con);
cmd.CommandType = CommandType.Text;
// cmd.Parameters.AddWithValue("#Id", value);
cmd.Connection = con;
//con.Open();
SqlDataReader dr = cmd.ExecuteReader();
while (dr.Read())
{
TextBox2.Text = dr["perwet"].ToString();
// DropDownList1.Items(DropDownList1.SelectedIndex).Text = dr["service"].ToString();
}
dr.Close();
//process 2
SqlCommand cmd2 = new SqlCommand("SELECT [orderid],[processid],[orgid],[processdesc] ,[perwet] FROM [anghan].[dbo].[ProcessOrder] where orderid='" + DropDownList1.SelectedItem.Value + "' and processid=2 ", con);
cmd2.CommandType = CommandType.Text;
// cmd.Parameters.AddWithValue("#Id", value);
cmd2.Connection = con;
//con.Open();
SqlDataReader dr2 = cmd2.ExecuteReader();
while (dr2.Read())
{
TextBox3.Text = dr2["perwet"].ToString();
// DropDownList1.Items(DropDownList1.SelectedIndex).Text = dr["service"].ToString();
}
dr2.Close();
Why do not you set the TextBox2 and TextBox3 to empty in the starting of the code . So that you do see what you have populated . Only those textbox value will be change where your code will reassign otherwise it will keep the old value.
just put like this>>
if(dr!=null)
{
while (dr.Read())
{
if((dr["perwet"]!=null)||(dr["perwet"].ToString()!=""))
TextBox2.Text = dr["perwet"].ToString();
else
TextBox2.Text="";
// DropDownList1.Items(DropDownList1.SelectedIndex).Text = dr["service"].ToString();
}
}
It will work.
What is wrong with this code? I want to catch the last value from SQL row and display it in a TextBox. Kindly help me.
private void textBox2_Leave(object sender, EventArgs e)
{
cmd.Connection = cn;
cmd.CommandType = CommandType.Text;
cmd.CommandText = "select last(remain) from item_new_customer where cust=" + textBox2.Text + "";
float h = (float)cmd.ExecuteScalar();
textBox20.Text = h.ToString();
}
cmd.CommandText = "select max(remain) from item_new_customer where cust='" + textBox2.Text + "'";
You are open for SQL-Injection, use parameters to avoid it.
To answer your actual question, i assume that you want this column: remain. But you want the value of the last inserted record. Since you haven't mentioned the column to detect the order of insertion, i use the primary key column (not recommended):
string sql = "SELECT TOP 1 remain FROM dbo.tablename WHERE cust=#cust ORDER BY id DESC";
using(var con = new SqlConnection(connectionString))
using(var cmd = new SqlCommand(sql, con))
{
cmd.Parameters.AddWithValue("#cust", textBox2.Text);
con.Open();
double h = (double)cmd.ExecuteScalar();
textBox20.Text = h.ToString();
}
You're missing a single quote after the textBox2.Text:
private void textBox2_Leave(object sender, EventArgs e)
{
cmd.Connection = cn;
cmd.CommandType = CommandType.Text;
cmd.CommandText =
"select max(remain) from item_new_customer where cust=" + textBox2.Text + "'";
//Missing tick here ^
float h = (float)cmd.ExecuteScalar();
textBox20.Text = h.ToString();
}
In addition, your code is an open invitation for SQL injection.
Thanks very much for all
My final right code is:
cmd.Connection = cn;
cmd.CommandType = CommandType.Text;
cmd.CommandText = "select top 1(remain) from item_new_customer where cust='"+textBox2.Text+"' order by id desc";
int h = (int)cmd.ExecuteScalar();
textBox20.Text = h.ToString();
What I would just do is put all of the SQL row values into a listbox and then take the text of the last item in the textbox and put that into a textbox. Keep the listbox hidden
private System.Windows.Forms.ListBox listBox1;
static SqlConnection connection = new SqlConnection(#"Data Source=hostname;Initial Catalog=database_name;Integrated Security=False;User ID=user;Password=123456;");
SqlDataAdapter adapter = new SqlDataAdapter("select * from table_name", connection);
DataTable table = new DataTable();
adapter.Fill(table);
foreach (DataRow row in table.Rows)
{
listBox1.Items.Add(row["row_name"].ToString());
}
textBox20.Text = listBox1.Items[listBox1.Items.Count - 1].ToString();