DropDownList always delete the first value? - c#

i'm creating a recipe website for meals. I make an admin panel and i want to delete a meal which i added before. And there is a menu which includes number of the meal. For example there are 4 meals in pasta category and it shows Pasta(4) at mainpage.
Me as an admin, if i would like to add a new meal to my website, it's working. I select a category and it's adding to that category. But for deleting, it's working wrong. It always delete the first value in DropDownList which is Meat Foods. Can you help me to find an answer?
Here is the code:
if (Page.IsPostBack == false)
{
id = Request.QueryString["YemekId"];
islem = Request.QueryString["islem"];
SqlCommand komut2 = new SqlCommand("Select *from Kategoriler", baglan.baglanti());
SqlDataReader oku2 = komut2.ExecuteReader();
DropDownList1.DataTextField = "KategoriAd"; //DropDownList'e kategorilerin adlarını text biçiminde oldukları için bu şekilde çektik.
DropDownList1.DataValueField = "KategoriId"; //DropDownList'e kategorilerin id nolarını value değerinde oldukları için bu şekilde çektik.
DropDownList1.DataSource = oku2;
DropDownList1.DataBind();
SqlCommand komut = new SqlCommand("Select *from Yemek", baglan.baglanti());
SqlDataReader oku = komut.ExecuteReader();
DataList1.DataSource = oku;
DataList1.DataBind();
}
//silme işlemi
if (islem == "sil")
{
SqlCommand komutsilme = new SqlCommand("Delete from Yemek where YemekId=#s1", baglan.baglanti());
komutsilme.Parameters.AddWithValue("#s1", id);
komutsilme.ExecuteNonQuery();
baglan.baglanti().Close();
SqlCommand kategorisil = new SqlCommand("Update Kategoriler set KategoriAdet=KategoriAdet-1 where KategoriId=#k1", baglan.baglanti());
kategorisil.Parameters.AddWithValue("#k1", DropDownList1.SelectedValue);
kategorisil.ExecuteNonQuery();
baglan.baglanti().Close();
Response.Write("<script> alert('Yemek başarıyla silindi!')</script>");
}

you are passing a id as a string from your query string to the parameter
komutsilme.Parameters.AddWithValue("#s1", id);
I am assuming YemekId is an int in your database so try this
komutsilme.Parameters.AddWithValue("#s1", int.Parse(id));
AddWithValue will derive the type of the parameter of its value, so ensure that it's the correct type, in this case int not string.

Related

C#: how to add 2 values in ComboBox from stored procedure

I have TWO questions, first how to add 2 values and second is: if we add 2 values so we need to change the code when we save combo-box value in database (second question with code I also ask from end of this question)?
I need to add 2 values from table dep_Id and dep_Name in `ComboBox; like this:
(Department ID: Department Name)
This is the stored procedure:
CREATE PROCEDURE [dbo]. SelectComoboxData_SP
AS
SELECT dep_Id, dep_Name
FROM department
RETURN 0
This is the C# code:
public void updateDepartmentList()
{
refresh_DataGridView();
SqlCommand cmd = new SqlCommand("SelectComoboxData_SP", con);
cmd.CommandType = CommandType.StoredProcedure;
con.Open();
try
{
SqlDataReader dr = cmd.ExecuteReader();
while (dr.Read())
{
com_boxDepartment.Items.Add(dr["dep_Id"]);
com_boxDepartment.SelectedIndex = 0;
}
dr.Close();
}
catch (Exception ex)
{
MessageBox.Show("<<<INVALID SQL OPERATION \n" + ex);
}
con.Close();
}
Let me also know when I select any department from the combobox so now I wrote this code
cmd.Parameters.AddWithValue("#dId", com_boxDepartment.Text);
for saving by id, so when add 2 values in combobox so we need to change anything?
If it were my C# I'd do it more like this (though I'd use strongly typed datasets)
public void updateDepartmentList()
{
refresh_DataGridView();
SqlCommand cmd = new SqlCommand("SelectComoboxData_SP", con);
cmd.CommandType = CommandType.StoredProcedure;
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataTable dt = new DataTable();
da.Fill(dt);
com_boxDepartment.DataSource = dt;
com_boxDepartment.DisplayMember = "dep_Name";
com_boxDepartment.ValueMember = "dep_Id";
}
Your combo will show "History Department" for example, but when you ask it for the .SelectedValue it will return e.g. 2 (the id for the history department)

if the content in the label matches a cell in a row C#

If the content in the label matches a cell content in 'column1' (the order ID column) of the database (similar concept to a login form), change value of cell 4 (the order location) in that specific row (and only that row) to specific value in textbox
if (result == DialogResult.Yes) // When the button is clicked and the user selects yes.
{
OleDbDataAdapter da = new OleDbDataAdapter("Select * from [Customer Orders] WHERE [Order ID] = #OrderId", MAcon);
da.SelectCommand.Parameters.AddWithValue("#OrderId", OleDbType.Integer);
// da.SelectCommand.Parameters.Add("#OrderId", OleDbType.Integer).Value = 2;
DataTable dtbl = new DataTable();
da.Fill(dtbl);
if (dtbl.Rows.Count == 1)
{
OleDbCommand cmd = new OleDbCommand("UPDATE [Customer Orders] SET [OrderStatus] = (#OrderStatus), [OrderID]= #OrderId", MAcon); //SET[Order Status] = (#OrderStatus)
MAcon.Open();
cmd.Parameters.AddWithValue("#OrderID", orderID);
cmd.Parameters.AddWithValue("#OrderStatus", Location.Text);
cmd.ExecuteNonQuery();
MAcon.Close();
MessageBox.Show("Production has begun");
}
could someone help me as of now, every cell in column 4 changes and I'm not sure what I've done wrong
This line:
OleDbCommand cmd = new OleDbCommand("UPDATE [Customer Orders] SET
[OrderStatus] = (#OrderStatus), [OrderID]= #OrderId", MAcon);
Needs a WHERE clause.
Based on your description in the question, possibly:
WHERE column1 = labelContent

How to get the data when I select a datagridview cell or column

I have 2 datagridview controls in a Windows Forms application.
I would like to get the info of a person when I select first datagridview cell or row to next datagridview:
try
{
ConnectionStringSettings consettings = ConfigurationManager.ConnectionStrings["attendancemanagement"];
string connectionString = consettings.ConnectionString;
SqlConnection con = new SqlConnection(connectionString);
con.Open();
adap3 = new SqlDataAdapter(#"SELECT Date,Attendance,Remarks FROM dailyattendance where employee_id='"+DailyGV.CurrentRow+"'", con);
ds3 = new DataSet();
adap3.Fill(ds3, "dailyattendance");
dataGridView1.DataSource = ds3.Tables[0];
}
Im trying the above code. But it's not working.
I'm not too sure what DailyGV.CurrentRow is but basically you can use the RowHeaderMouseClick...see MSDN documentation. To use it, hook an event handler to it when initializing the form components (you can use VS designer as well...
dataGridView1.RowHeaderMouseClick += dataGridView1_RowHeaderMouseClick;
void dataGridView1_RowHeaderMouseClick(
object sender, DataGridViewCellMouseEventArgs e)
{
}
this event handler will get fired everytime you select a row header in the DataGridView control which will pass information about the event through an instance of the DataGridViewCellMouseEventArgs class (see MSDN documentation). This argument has a RowIndex property that provides the index of the row clicked which you can use to retrieve the values of the cells in that row...including the person id (if provided)...for example...
void dataGridView1_RowHeaderMouseClick(
object sender, DataGridViewCellMouseEventArgs e)
{
string personId = dataGridView1.Rows[e.RowIndex].Cells["PersonId"].Value;
//TODO: implement your own query to retrieve data for that person id
}
notice that you need to provide a proper column name when access the cells collection indexer...Cells["columnName"]
I will not give any description about the solution because Leo and Arsalan Bhatti has already suggested the solution. I am just telling you how your code should looks like and how it should be written.
string connectionString = consettings.ConnectionString;
using (SqlConnection con = new SqlConnection(connectionString))
{
try
{
con.Open();
string empID = DailyGV.CurrentRow.Cells["employee_id"].Value.ToString();
SqlCommand Cmd = con.CreateCommand();
Cmd.CommandText = "SELECT Date,Attendance,Remarks FROM dailyattendance where employee_id=#employee_id";
Cmd.Parameters.Add("#employee_id", SqlDbType.Int).Value = Int32.Parse(empID);
adap3 = new SqlDataAdapter(Cmd);
DataTable dt = new DataTable();
adap3.Fill(dt);
dataGridView1.DataSource = dt;
con.Close();
}
catch
{}
}
try
{
cn.Open();
string query = "select employee_id,Employee_Name,Image_of_Employee from Employee_Details where employee_id='" + dataGridView1.SelectedCells[0].Value.ToString() + "'";
SqlCommand cmd = new SqlCommand(query, cn);
SqlDataReader sdr;
sdr = cmd.ExecuteReader();
if (sdr.Read())
{
string aa = (string)sdr["employee_id"];
string bb = (string)sdr["employee_name"];
txtEmployeeID.Text = aa.ToString();
txtnameofemployee.Text = bb.ToString();
byte[] img=(byte[])sdr["Image_of_employee"];
MemoryStream ms=new MemoryStream(img);
ms.Seek(0,SeekOrigin.Begin);
pictureBox1.Image=Image.FromStream(ms); cn.Close();
}
}
catch (Exception e1)
{
MessageBox.Show(e1.Message);
}
You are passing the current row's index as employee id in SELECT query. Pass employee id for the selected record. Then it will work fine.

getting an error when trying to find value in database

So I have a textbox and a button. I want to enter a value into the textbox and it will find the value that i entered in the row from the table called 'ticket'. I also then want to create a 'rebate slip' object in a table called 'Rebateslip'. This table has 2 fields - an id which is autoincremented and the ticketId which is the value I entered in the textbox (so basically I'm just passing the ticketId I just found into the 'RebateSlip' table). I put all the functions in a class called 'model' then I call them in the button event handler.
public bool rebateslip(int ticketID)
{
SqlCommand myCommand = new SqlCommand("SELECT ID FROM ticket WHERE ID = #ticketID", con);
SqlDataAdapter sqlDa = new SqlDataAdapter(myCommand);
myCommand.Parameters.AddWithValue("#ticketID", ticketID);
var reader = myCommand.ExecuteReader();
return reader.HasRows;
}
public void createRebateslip(int ticketId)
{
SqlCommand myCommand = new SqlCommand("INSERT INTO RebateSlip (ticketId) VALUES (#ticketId); SELECT SCOPE_IDENTITY();", con);
myCommand.Parameters.AddWithValue("#ticketId", ticketId);
string insertID = (myCommand.ExecuteScalar()).ToString();
rebateSlipList.Add(new RebateSlip(Int32.Parse(insertID), ticketId));
}
It works for one number but if I try enter another number into the textbox I get the error there is already an open DataReader associated with command which must be closed first.
Here's the code for the button. If the value is found in the table then a 'rebatelip' should be created but that is also not working.
private void buttonPrintRebateSlip_Click(object sender, EventArgs e)
{
int id;
if (!int.TryParse(textBoxRebateSlip.Text, out id))
{
return;
}
if (model.rebateslip(id))
{
MessageBox.Show("Found ticket");
//create rebate slip object
model.createRebateslip(id);
textBoxRebateSlip.Clear();
}
else
{
MessageBox.Show("Ticket not in database");
textBoxRebateSlip.Clear();
}
}
Excerpt from SqlDataReader.Close Method:
You must explicitly call the Close method when you are through using
the SqlDataReader to use the associated SqlConnection for any other
purpose.
You should use the using Statement.
public bool rebateslip(int ticketID)
{
using(SqlCommand myCommand = new SqlCommand("SELECT ID FROM ticket WHERE ID = #ticketID", con))
{
using(SqlDataAdapter sqlDa = new SqlDataAdapter(myCommand))
{
myCommand.Parameters.AddWithValue("#ticketID", ticketID);
using(var reader = myCommand.ExecuteReader())
{
return reader.HasRows;
}
}
}
}
Anyway, your sqlDa SqlDataAdapter makes no sense in the context. Probably you only need:
public bool rebateslip(int ticketID)
{
using(SqlCommand myCommand = new SqlCommand("SELECT ID FROM ticket WHERE ID = #ticketID", con))
{
myCommand.Parameters.AddWithValue("#ticketID", ticketID);
using(var reader = myCommand.ExecuteReader())
{
return reader.HasRows;
}
}
}
reader.close once you're done with it.
Also -- you should use a using or try...catch block
This way you never have a reader variable. Still the using paradigm is better.
public bool rebateslip(int ticketID)
{
SqlCommand myCommand = new SqlCommand("SELECT ID FROM ticket WHERE ID = #ticketID", con);
SqlDataAdapter sqlDa = new SqlDataAdapter(myCommand);
myCommand.Parameters.AddWithValue("#ticketID", ticketID);
return myCommand.ExecuteReader().HasRows;
}
public void createRebateslip(int ticketId)
{
SqlCommand myCommand = new SqlCommand("INSERT INTO RebateSlip (ticketId) VALUES (#ticketId); SELECT SCOPE_IDENTITY();", con);
myCommand.Parameters.AddWithValue("#ticketId", ticketId);
int insertID = (int)myCommand.ExecuteScalar();
rebateSlipList.Add(new RebateSlip(insertID, ticketId));
}
Also it seems you are storing ticketID's in the Insert table (from insertID) and insertID's in the Ticket table (from ticketID). Instead you should use a third table where you store only insertID's and ticketID's, allowing a multiple to multiple relationships while allowing them to be changed/deleted with a single action.

Unable to retrieve the productName accordingly to what user click

I am retrieving one of my column table's values and store it in a Label. After storing it in a Label, I will session the Label over to another page. However, the values i am retrieving must be according to what the user click. For example, User click the 2nd product in my webpage. So the name of the second product have to be session over to the next page.
My problem here is that I managed to retrieve the values but it is not according to what the user click. The output of my Label came out to be all the product name which is not i want it to be. Where have i gone wrong?
Here is my .cs code:
string strConnectionString = ConfigurationManager.ConnectionStrings["PRODUCTSConnectionString"].ConnectionString;
SqlConnection myConnect = new SqlConnection(strConnectionString);
string strCommandText = "SELECT productName from Products";
SqlCommand cmd = new SqlCommand(strCommandText, myConnect);
myConnect.Open();
SqlDataReader reader = cmd.ExecuteReader();
Label1.Text = "";
while (reader.Read())
{
Label1.Text += reader["productName"].ToString() + "<br/>";
}
reader.Close();
myConnect.Close();
You want to capture the unique identifier of the product that the user selected (your primary key for example) and then add a WHERE clause to your SELECT statement that filters on that product id. Currently, your SELECT statement is retrieving the product name for all products in your table.
If you are expecting one product from your database you can change the while to if
string strCommandText = "SELECT productName from Products WHERE productID=#ProductID";
SqlCommand cmd = new SqlCommand(strCommandText, myConnect);
cmd.Parameters.AddWithValues("#ProductID", productID);
...
if(reader.Read())
{
//Label1.Text += reader["productName"].ToString();
Label1.Text = reader["productName"].ToString();
}
But I think ProductID should be unique

Categories