I have got a problem.
I need to get id_subcategoria in 2 combobox "1". I have this code:
void fill_cbsubcategoria(int masterId)
{
cbsubcategoria.Items.Clear();
cbproduto.Items.Clear();
cbproduto.Text = "Escolha o produto";
txtquantidade.Text = null;
txtpreco.Text = null;
txtiva.Text = null;
try
{
con.Open();
string Query = "select * from Subcategoria where id_categoria = #mid";
SqlCommand createCommand = new SqlCommand(Query, con);
createCommand.Parameters.AddWithValue("#mid", masterId);
SqlDataReader dr = createCommand.ExecuteReader();
while (dr.Read())
{
int id_subcategoria = (int)dr.GetInt32(0);
string subcategoria = (string)dr.GetString(1);
cbsubcategoria.Items.Add(id_subcategoria.ToString() + " - " + new SubCategoriaHolder(id_subcategoria, subcategoria));
}
con.Close();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
And I need to have id_subcategoria, when clicking at "Guardar".
private void btnguardar_Click(object sender, EventArgs e)
{
try
{
con.Open();
string Query = "insert into dbPAP.Produtos (id_subcategoria, nome_produto, quantidade, preco_unitario, iva, imagem)" + "values('" + "I NEED THAT ID FROM COMBOBOX" + this.txt_nproduto.Text + this.txtquantidade.Text + this.txtpreco.Text + this.txtiva.Text + "') ;";
SqlCommand createCommand = new SqlCommand(Query, con);
SqlDataReader dr = createCommand.ExecuteReader();
MessageBox.Show("Adicionado com sucesso!");
while (dr.Read())
{
}
con.Close();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
Here's my button guardar code.
Note: I don't want SelectedValue from combobox, I want to get id_subcategoria from DataBase.
Just add the ID's to a array List, while loading the elements to the combo Box, the Selected index from the combo box should reference to the according id in the List
Related
protected void btnDeleteVenue_Click(object sender, EventArgs e)
{
try
{
con.Open();
string ddl = DropDownList1.SelectedItem.Value;
string sq = "select venue_name from Venue";
cmd = new SqlCommand(sq, con);
SqlDataReader r = cmd.ExecuteReader();
string dq = null;
if (r.HasRows)
{
while (r.Read())
{
if (ddl.Equals(r.GetValue(0).ToString()))
{
string dq = "DELETE from Venue WHERE venue_name=" + ddl;
//.Close();
cmd = new SqlCommand(dq, con);
cmd.ExecuteNonQuery();
Response.Write("<script> alert('Venue Deleted') </script>");
con.Close();
}
}
}
}
catch(Exception ex)
{
Response.Write(ex);
}
}
Change this line to. A string must be quoted.
string dq = "DELETE from Venue WHERE venue_name='" + ddl + "'";
I want to draw a stacked chart from mysql database.
I want to have 4 columns named "port1", "port2", "port3" and "port4".
My problem is when I import the data from my DB, I check the type a column in the table then I draw the chart . My DB contains 4 types of port consequently I would have 4 columns named port1, port2, port3 and port4, but my code generate all the data but on the same column which is port1.
How can I add an identical number of datapoints?
try
{
con.Open();
string query1 = "SELECT type,name,value FROM " + server + " WHERE type LIKE '%port1'" ;
string query4 = "SELECT type,name,value FROM " + server + " WHERE type LIKE '%port4'";
SqlCommand cmmd = new SqlCommand(query1, con);
SqlCommand cmmd4 = new SqlCommand(query4, con);
SqlDataReader dataReader = cmmd.ExecuteReader();
while (dataReader.Read())
{
chart1.Series.Add(dataReader["name"].ToString());
chart1.Series[dataReader["name"].ToString()].ChartType = SeriesChartType.StackedColumn;
chart1.Series[dataReader["name"].ToString()]["StackedGroupName"] = "Group1";
chart1.Series[dataReader["name"].ToString()].Points.AddXY((dataReader["type"].ToString()), dataReader["value"].ToString());
}
con.Close();
}
catch (Exception ex)
{
MessageBox.Show("Error " + ex);
}
try
{
con.Open();
string query1 = "SELECT type,name,value FROM " + server + " WHERE type LIKE '%port1'" ;
SqlCommand cmmd = new SqlCommand(query1, con);
SqlDataReader dataReader = cmmd.ExecuteReader();
while (dataReader.Read())
{
chart1.Series.Add(dataReader["name"].ToString());
chart1.Series[dataReader["name"].ToString()].ChartType = SeriesChartType.StackedColumn;
chart1.Series[dataReader["name"].ToString()]["StackedGroupName"] = "Group1";
chart1.Series[dataReader["name"].ToString()].Points.AddXY((dataReader["type"].ToString()), dataReader["value"].ToString());
}
con.Close();
}
catch (Exception ex)
{
MessageBox.Show("Error " + ex);
}
try
{
con.Open();
string query2 = "SELECT type,name,value FROM " + server + " WHERE type LIKE '%port2'";
SqlCommand cmmd2 = new SqlCommand(query2, con);
SqlDataReader dataReader2 = cmmd2.ExecuteReader();
while (dataReader2.Read())
{
chart1.Series.Add(dataReader2["name"].ToString());
chart1.Series[dataReader2["name"].ToString()].ChartType = SeriesChartType.StackedColumn;
chart1.Series[dataReader2["name"].ToString()]["StackedGroupName"] = "Group2";
// MessageBox.Show(dataReader2["type"].ToString());
chart1.DataBind();
chart1.Series[dataReader2["name"].ToString()].Points.AddXY("Port_2", dataReader2["value"].ToString());
chart1.Series[dataReader2["name"].ToString()]["PointWidth"] = "1";
}
con.Close();
}
catch(Exception ex)
{
MessageBox.Show("Error "+ ex);
}
I made a project using c# and data base using access accdb and connected between them both. I made 2 buttons, first one to add new costumer, which works perfectly, and second one to update the data of the costumer (first name and last name), for some reason, the update button does not work, there is no error when I run the project, but after I click nothing happens...
private void button2_Click(object sender, EventArgs e)
{
connect.Open();
string cid = textBox1.Text;
string cfname = textBox2.Text;
string clname = textBox3.Text;
OleDbCommand command = new OleDbCommand();
command.Connection = connect;
command.CommandText = "UPDATE Tcostumers SET cfname= " + cfname + "clname= " + clname + " WHERE cid = " + cid;
if (connect.State == ConnectionState.Open)
{
try
{
command.ExecuteNonQuery();
MessageBox.Show("DATA UPDATED");
connect.Close();
}
catch (Exception expe)
{
MessageBox.Show(expe.Source);
connect.Close();
}
}
else
{
MessageBox.Show("ERROR");
}
}
I believe your commandtext is where the trouble lies;
command.CommandText = "UPDATE Tcostumers SET cfname= " + cfname + "clname= " + clname + " WHERE cid = " + cid;
You require a comma between the set statements, and also as Gino pointed out the speechmarks.
Edit:
It's better than you use parameters for your variables, your current method is open to SQL injection, eg.
private void button2_Click(object sender, EventArgs e)
{
OleDbCommand command = new OleDbCommand(#"UPDATE Tcostumers
SET cfname = #CFName,
clname = #CLName
WHERE cid = #CID", connect);
command.Parameters.AddWithValue("#CFName", textBox2.Text);
command.Parameters.AddWithValue("#CLName", textBox3.Text);
command.Parameters.AddWithValue("#CID", textBox1.Text);
try
{
connect.Open();
}
catch (Exception expe)
{
MessageBox.Show(expe.Source);
}
try
{
command.ExecuteNonQuery();
MessageBox.Show("DATA UPDATED");
}
catch (Exception expe)
{
MessageBox.Show(expe.Source);
}
finally
{
connect.Close();
}
}
Its how I tend to format my code, so do as you will with it. Hope it helps.
It might be a stupid thing but...
you're updating strings not ints so try adding '' to your strings something like:
command.CommandText = "UPDATE Tcostumers SET cfname= '" + cfname + "' clname='" + clname + "' WHERE cid = " + cid;
//my sample code for edit/update
Table Name = StudentFIle
Fields = id,fname,lname
bool found = false;
OleDbConnection BOMHConnection = new OleDbConnection(connect);
string sql = "SELECT * FROM StudentFIle";
BOMHConnection.Open();
OleDbCommand mrNoCommand = new OleDbCommand(sql, BOMHConnection);
OleDbDataReader mrNoReader = mrNoCommand.ExecuteReader();
while (mrNoReader.Read())
{
if (mrNoReader["id"].ToString().ToUpper().Trim() == idtextbox.Text.Trim())
{
mrNoReader.Close();
string query = "UPDATE StudentFIle set fname='" +firstnametextbox.Text+ "',lname='"+lastnametextbox.Text+"' where id="+idtextbox.Text+" ";
mrNoCommand.CommandText = query;
mrNoCommand.ExecuteNonQuery();
MessageBox.Show("Successfully Updated");
found = true;
break;
}
continue;
}
if (found == false)
{
MessageBox.Show("Id Doesn't Exist !.. ");
mrNoReader.Close();
BOMHConnection.Close();
idtextbox.Focus();
}
I have filled the drop down menu with names from the my UserData database. I am currently trying to select an users name to make their user details appear in the textboxes, however when I try to select an option from the dropdown menu, the first option always appears in the textboxes I was wondering if anybody could see a problem in my code?
protected void BtnSelect_Click(object sender, EventArgs e)
{
SqlDataReader reader;
String connString = ConfigurationManager
.ConnectionStrings["RegistrationConnectionString"].ConnectionString;
SqlConnection conn = new SqlConnection(connString);
SqlCommand comm1 = new SqlCommand(
"SELECT FirstName, LastName, Email FROM UserData " +
"WHERE TeacherID = #TeacherID", conn);
comm1.Parameters.Add("#TeacherID", System.Data.SqlDbType.Int);
comm1.Parameters["#TeacherID"].Value = DropDownList1.SelectedItem.Value;
try
{
conn.Open();
reader = comm1.ExecuteReader();
if (reader.Read())
{
txtFirstName.Text = reader["FirstName"].ToString();
txtLastName.Text = reader["LastName"].ToString();
txtEmail.Text = reader["Email"].ToString();
}
reader.Close();
}
catch (Exception ex)
{
dbErrorLabel.Text = ("Error in retrieval"+ ex.StackTrace);
}
finally
{
conn.Close();
}
}
Try altering your code slightly like this and then you will find it easier to debug. Check what value you're getting for the selected value (is it what you expect) and also what the content of the actual exception is that you're getting.
This should help you to work out what's going on.
protected void BtnSelect_Click(object sender, EventArgs e)
{
SqlDataReader reader;
String connString = ConfigurationManager
.ConnectionStrings["RegistrationConnectionString"].ConnectionString;
SqlConnection conn = new SqlConnection(connString);
SqlCommand comm1 = new SqlCommand(
"SELECT FirstName, LastName, Email FROM UserData " +
"WHERE TeacherID = #TeacherID", conn);
var selectedValue = DropDownList1.SelectedItem.Value;
var selected = int.Parse(selectedValue);
comm1.Parameters.Add("#TeacherID", System.Data.SqlDbType.Int);
comm1.Parameters["#TeacherID"].Value = selected;
try
{
conn.Open();
reader = comm1.ExecuteReader();
if (reader.Read())
{
txtFirstName.Text = reader["FirstName"].ToString();
txtLastName.Text = reader["LastName"].ToString();
txtEmail.Text = reader["Email"].ToString();
}
reader.Close();
}
catch(Exception ex)
{
dbErrorLabel.Text = ("Error in retrieval " + ex.StackTrace );
}
finally
{
conn.Close();
}
}
I want to edit the dataGridView as well as dataBase.
I have an button when i click it after editing the dataGridview it will updated database.
My first row obly updated but others row doesn't.
here is my code
private void button2_Click(object sender, EventArgs e)
{
try
{
foreach (DataGridViewRow row in dataGridView1.Rows)
{
string id = row.Cells["Product ID"].Value.ToString();
string name = row.Cells["Product Name"].Value.ToString();
string description = row.Cells["Product Description"].Value.ToString();
string category = row.Cells["Category"].Value.ToString();
string quantity = row.Cells["QTY"].Value.ToString();
string buyPrice = row.Cells["Buy Price"].Value.ToString();
string sellPrice = row.Cells["Sell Price"].Value.ToString();
string date = row.Cells["Date"].Value.ToString();
String query = "UPDATE [Stock List Table3] SET [Product Name] = '" + name + "',[Product Description] = '" + description + "',[Category] = '" + category + "',[QTY] = '" + quantity + "',[Buy Price] = '" + buyPrice + "',[Sell Price] = '" + sellPrice + "',Date = '" + date + "' WHERE [Product ID] = '" + id + "'";
m.Update_By_DataGridView_Information(query);
m.Load_Table1(dataGridView1);
m.Load_Table1(dataGridView4);
}
}
catch (Exception ex)
{
//MessageBox.Show(ex.Message);
}
}
public void Load_Table1(DataGridView dv)
{
string query = "SELECT * FROM [Stock List Table3]";
SqlConnection Conn = create_connection();
SqlCommand cmd = new SqlCommand(query, Conn);
try
{
SqlDataAdapter sda = new SqlDataAdapter();
sda.SelectCommand = cmd;
DataTable dataset = new DataTable();
sda.Fill(dataset);
BindingSource bSource = new BindingSource();
bSource.DataSource = dataset;
dv.DataSource = bSource;
sda.Update(dataset);
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
public void Update_By_DataGridView_Information(string query)
{
try
{
SqlConnection Conn = create_connection();
SqlCommand cmd = new SqlCommand(query, Conn);
cmd.ExecuteNonQuery();
Conn.Close();
//MessageBox.Show("Updated Product Information Successfully", "Confirmation", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
Here is my total code Error Line catch block in button2
After updating first row you update datagridview1 with original data
m.Load_Table1(dataGridView1)
Then next rows was updated with same values...
Try to put Load method outside of foreach loop:
foreach (DataGridViewRow row in dataGridView1.Rows)
{
//your update code for row...
}
m.Load_Table1(dataGridView1);
m.Load_Table1(dataGridView4);