I am trying to select film by using on select command, print the title in a label once selected.. that works well.
next part is the selected film will then decrement 1 from the database stock on button click. This is where I think I am getting confused, its showing no errors until the button click takes place.
C# code for update query
protected void Button2_Click(object sender, EventArgs e)
{
var myquery = string.Format("UPDATE DVD SET Stock = Stock - 1");
da.InsertCommand = new OleDbCommand("INSERT INTO DVD (Stock) VALUES (#MessageLabel)", conn);
{
da.InsertCommand.Parameters.AddWithValue("#Stock", MessageLabel.Text);
conn.Open();
da.InsertCommand.ExecuteNonQuery();
using (OleDbCommand cmd = new OleDbCommand(myquery, conn))
cmd.ExecuteNonQuery();
conn.Close();
conn.Dispose();
}
}
Previous code for select event
public void Latest_DVD()
{
{
using (OleDbDataAdapter dataquer = new OleDbDataAdapter("SELECT Title,Category,Director,Stock,Year FROM DVD ", conn))
{
dataquer.Fill(dt);
}
}
DG_Latest.ShowHeader = true;
DG_Latest.DataSource = dt;
DG_Latest.DataBind();
conn.Close();
conn.Dispose();
}
protected void Latest_DVD_SelectedIndexChanged(Object sender, EventArgs e)
{
GridViewRow row = DG_Latest.SelectedRow;
MessageLabel.Text = "You selected to rent " + row.Cells[1].Text + ".";
}
so I am thinking I have the query wrong and possibly nor retrieve the update from the label but maybe the on select its self... I am not sure through.
the error it is showing is
Data type mismatch in criteria expression.
just after the connection is open
As #afzalulh said, remove the insert part. And change myquery string to be:
var myquery = string.Format("UPDATE DVD SET Stock = Stock - 1 WHERE Title = #Title");
var row = DB_Latest.SelectedRow;
var title = row.Cells[0].Text;
var cmd = new OleDbCommand(myquery, conn);
cmd.Parameters.AddWithValue("#Title", title);
With that, you only update Stock for the selected DVD title only. Without adding WHERE clause, the query will decrease stock for all DVDs.
You want to update stock, there's no need to insert. I believe this is what you want:
protected void Button2_Click(object sender, EventArgs e)
{
var myquery = string.Format("UPDATE DVD SET Stock = Stock - 1");
conn.Open();
using (OleDbCommand cmd = new OleDbCommand(myquery, conn))
cmd.ExecuteNonQuery();
conn.Close();
conn.Dispose();
}
EDIT: myquery should include WHERE as suggested by har07. Otherwise it will reduce all DVD's stock by 1.
Related
I have written this C# application that acts as a database to keep track of projects and notes on the projects. I had it all working fine but then I needed to change the ProjectID column to not be an integer value (the project id's start with letters) so I had to add a new column to be able to accept this.
I kept the old project ID and renamed it "Project_ID_Backend" so my code would still work. (The way I have it written was that if the Project ID was greater than 0, things would happen.
Now whenever I click on the datagridview I am getting an error message. It used to work where when you would click on the datagridview, the contents of that row in the grid would populate the textboxes automatically making it easy to make changes to the records.
using System;
using System.Windows.Forms;
using System.Data.SqlClient;
using System.Data;
using System.Collections.Generic;
namespace SFTool
{
public partial class MainForm : Form
{
public MainForm()
{
InitializeComponent();
}
SqlConnection con = new SqlConnection("my connection string here");
public int ProjectIDBackend;
public int NoteID;
private void MainForm_Load(object sender, System.EventArgs e)
{
// load in sql data to the data grid view
GetProjectsDataset();
// load notes database into the notesDataGridView
GetNotesDataset();
PopulateListBoxes();
}
private void PopulateListBoxes()
{
List<string> ProjectStatusList = new List<string>();
ProjectStatusList.Add("Working");
ProjectStatusList.Add("Submitted");
ProjectStatusList.Add("Reviewed");
ProjectStatusList.Add("Completed");
projectStatusListBox.DataSource = ProjectStatusList;
List<string> ProjectTypeList = new List<string>();
ProjectTypeList.Add("New build");
ProjectTypeList.Add("MAC");
ProjectTypeList.Add("Decom");
projectTypeListBox.DataSource = ProjectTypeList;
}
private void GetNotesDataset()
{
SqlCommand cmd = new SqlCommand("SELECT * FROM sfNotes", con);
DataTable dtNotes = new DataTable();
con.Open();
SqlDataReader sdr = cmd.ExecuteReader();
dtNotes.Load(sdr);
con.Close();
notesDataGridView.DataSource = dtNotes;
// Automatically resizes the columns to fit the data grid view
notesDataGridView.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.Fill;
notesDataGridView.AutoSizeRowsMode = DataGridViewAutoSizeRowsMode.None;
}
private void GetProjectsDataset()
{
SqlCommand cmd = new SqlCommand("SELECT Project_ID AS 'Project ID', First_Name AS 'First Name', Last_Name AS 'Last Name', Project_Type AS 'Type', Project_Status AS 'Project Status', Last_Updated AS 'Last Updated', Last_Updated_By AS 'Last Updated By', Project_ID_Backend AS 'P.ID Backend' " +
"FROM sfProjects", con);
DataTable dt = new DataTable();
con.Open();
SqlDataReader sdr = cmd.ExecuteReader();
dt.Load(sdr);
con.Close();
dataGridView.DataSource = dt;
// Automatically resizes the columns to fit the data grid view
dataGridView.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.Fill;
dataGridView.AutoSizeRowsMode = DataGridViewAutoSizeRowsMode.None;
}
private void insertButton_Click(object sender, EventArgs e)
{
// allow user to insert data into the database, or create new records
if (IsValid())
{
SqlCommand cmd = new SqlCommand("INSERT INTO sfProjects VALUES (#Project_ID, #FirstName, #LastName, #Project_Type, #Project_Status, #Last_Updated, #Last_Updated_By)", con);
cmd.CommandType = CommandType.Text;
cmd.Parameters.AddWithValue("#Project_ID", projectIDTextBox.Text);
cmd.Parameters.AddWithValue("#FirstName", firstNameTextBox.Text); // maps #FirstName to the firstName textbox
cmd.Parameters.AddWithValue("#LastName", lastNameTextBox.Text);
cmd.Parameters.AddWithValue("#Project_Type", projectTypeListBox.SelectedItem);
cmd.Parameters.AddWithValue("#Last_Updated", DateTime.Now);
cmd.Parameters.AddWithValue("#Last_Updated_By", System.Environment.MachineName);
cmd.Parameters.AddWithValue("#Project_Status", projectStatusListBox.SelectedItem);
con.Open();
cmd.ExecuteNonQuery();
con.Close();
MessageBox.Show("New record has been successfully added to the database", "Saved", MessageBoxButtons.OK, MessageBoxIcon.Information);
// now update/REFRESH the database so it shows the new record
GetProjectsDataset();
// reset form controls
ResetFormControls();
}
}
// data validation. (Make sure name is never empty)
private bool IsValid()
{
if (firstNameTextBox.Text == string.Empty)
{
MessageBox.Show("First Name is required.", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
return false;
}
// else return true (it is valid)
return true;
}
private bool IsNotesValid()
{
if (notesProjectIDTextBox.Text == string.Empty)
{
MessageBox.Show("Project ID is required in order to assign a note to a project.", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
return false;
}
// else return true (it is valid/Project ID was provided)
return true;
}
private void resetButton_Click(object sender, EventArgs e)
{
// resets, or clears, the textboxes
ResetFormControls();
GetProjectsDataset();
GetNotesDataset();
}
private void ResetFormControls()
{
ProjectIDBackend = 0; // resets value of projectID after clicking reset
projectIDTextBox.Clear();
firstNameTextBox.Clear();
lastNameTextBox.Clear();
projectTypeListBox.ClearSelected();
projectStatusListBox.ClearSelected();
notesProjectIDTextBox.Clear();
notesTextBox.Clear();
searchProjectsTextBox.Clear();
projectIDTextBox.Focus();
}
private void dataGridView_CellClick(object sender, DataGridViewCellEventArgs e)
{
// WHen you click on a row in the data grid, the textboxes will automatically populate with that rows values
ProjectIDBackend = Convert.ToInt32(dataGridView.SelectedRows[0].Cells[7].Value);
projectIDTextBox.Text = dataGridView.SelectedRows[0].Cells[0].Value.ToString();
firstNameTextBox.Text = dataGridView.SelectedRows[0].Cells[1].Value.ToString();
lastNameTextBox.Text = dataGridView.SelectedRows[0].Cells[2].Value.ToString();
projectTypeListBox.SelectedItem = dataGridView.SelectedRows[0].Cells[3].Value.ToString();
projectStatusListBox.SelectedItem = dataGridView.SelectedRows[0].Cells[4].Value.ToString();
// Filter the notes grid to only show notes for the row the user clicks
SqlCommand cmd = new SqlCommand("SELECT * FROM sfNotes WHERE Project_ID_Backend= #Project_ID_Backend", con);
cmd.CommandType = CommandType.Text;
cmd.Parameters.AddWithValue("#Project_ID_Backend", this.ProjectIDBackend);
con.Open();
cmd.ExecuteNonQuery();
con.Close();
DataTable dtF = new DataTable();
con.Open();
SqlDataReader sdr = cmd.ExecuteReader();
dtF.Load(sdr);
con.Close();
notesDataGridView.DataSource = dtF;
// Automatically resizes the columns to fit the data grid view
notesDataGridView.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.Fill;
notesDataGridView.AutoSizeRowsMode = DataGridViewAutoSizeRowsMode.None;
}
private void updateButton_Click(object sender, EventArgs e)
{
if (ProjectIDBackend > 0)
{
SqlCommand cmd = new SqlCommand("UPDATE sfProjects SET Project_ID= #Project_ID, First_Name= #First_Name, Last_Name= #Last_Name, Project_Type= #Project_Type, Project_Status= #Project_Status, Last_Updated= #Last_Updated, Last_Updated_By= #Last_Updated_By WHERE Project_ID= #Project_ID", con);
cmd.CommandType = CommandType.Text;
cmd.Parameters.AddWithValue("#Project_ID", projectIDTextBox.Text);
cmd.Parameters.AddWithValue("#First_Name", firstNameTextBox.Text);
cmd.Parameters.AddWithValue("#Last_Name", lastNameTextBox.Text);
cmd.Parameters.AddWithValue("#Project_Type", projectTypeListBox.SelectedItem);
cmd.Parameters.AddWithValue("#Project_Status", projectStatusListBox.SelectedItem);
cmd.Parameters.AddWithValue("#Last_Updated", DateTime.Now);
cmd.Parameters.AddWithValue("#Last_Updated_By", System.Environment.MachineName);
cmd.Parameters.AddWithValue("#Project_ID_Backend", this.ProjectIDBackend);
con.Open();
cmd.ExecuteNonQuery();
con.Close();
MessageBox.Show("Record is successfully updated", "Updated", MessageBoxButtons.OK, MessageBoxIcon.Information);
// now update/REFRESH the database so it shows the new record
GetProjectsDataset();
// reset form controls
ResetFormControls();
}
else
{
MessageBox.Show("Please select a record to update", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
private void deleteButton_Click(object sender, EventArgs e)
{
// Confirm user wants to delete by asking "Are you sure?"
var confirmDelete = MessageBox.Show("Are you sure you want to delete this record? This action cannot be undone.",
"Confirm Delete",
MessageBoxButtons.YesNo,
MessageBoxIcon.Warning);
if (confirmDelete == DialogResult.Yes)
{
if (ProjectIDBackend > 0)
{
SqlCommand cmd = new SqlCommand("DELETE FROM sfProjects WHERE Project_ID_Backend= #Project_ID_Backend", con);
cmd.CommandType = CommandType.Text;
cmd.Parameters.AddWithValue("#Project_ID_Backend", this.ProjectIDBackend); // Project_ID equals "this" ProjectID that I clicked on
con.Open();
cmd.ExecuteNonQuery();
con.Close();
MessageBox.Show("Record is successfully deleted from the system", "Updated", MessageBoxButtons.OK, MessageBoxIcon.Information);
// now update/REFRESH the database so it shows the new record
GetProjectsDataset();
// reset form controls
ResetFormControls();
}
else
{
MessageBox.Show("Please select a record to delete", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
else
{
}
}
private void notesButton_Click(object sender, EventArgs e)
{
// Addes note into the database
if (IsNotesValid())
{
SqlCommand cmd = new SqlCommand("INSERT INTO sfNotes VALUES (#Project_ID, #Notes, #Note_Created, #Note_Created_By)", con);
cmd.CommandType = CommandType.Text;
cmd.Parameters.AddWithValue("#Project_ID", notesProjectIDTextBox.Text); // maps #Project_ID to the notesProjectID textbox
cmd.Parameters.AddWithValue("#Notes", notesTextBox.Text);
cmd.Parameters.AddWithValue("#Note_Created", DateTime.Now);
cmd.Parameters.AddWithValue("#Note_Created_By", System.Environment.MachineName);
con.Open();
cmd.ExecuteNonQuery();
con.Close();
MessageBox.Show("New note has been successfully added to the database for Project ID " + this.ProjectIDBackend, "Saved", MessageBoxButtons.OK, MessageBoxIcon.Information);
// now update/REFRESH the database so it shows the new record
GetProjectsDataset();
GetNotesDataset();
// reset form controls
ResetFormControls();
}
}
private void notesDataGridView_CellClick(object sender, DataGridViewCellEventArgs e)
{
// WHen you click on a row in the data grid, the textboxes will automatically populate with that rows values
NoteID = Convert.ToInt32(notesDataGridView.SelectedRows[0].Cells[0].Value);
notesProjectIDTextBox.Text = notesDataGridView.SelectedRows[0].Cells[1].Value.ToString();
notesTextBox.Text = notesDataGridView.SelectedRows[0].Cells[2].Value.ToString();
}
private void removeNote_Click(object sender, EventArgs e)
{
// Confirm user wants to delete by asking "Are you sure?"
var confirmDelete = MessageBox.Show("Are you sure you want to delete this note? This action cannot be undone.",
"Confirm Delete",
MessageBoxButtons.YesNo,
MessageBoxIcon.Warning);
if (confirmDelete == DialogResult.Yes)
{
if (NoteID > 0)
{
SqlCommand cmd = new SqlCommand("DELETE FROM sfNotes WHERE Note_ID= #Note_ID", con);
cmd.CommandType = CommandType.Text;
cmd.Parameters.AddWithValue("#Note_ID", this.NoteID); // #Note_ID equals "this" NoteID that I clicked on
con.Open();
cmd.ExecuteNonQuery();
con.Close();
MessageBox.Show("Note is successfully deleted from the system", "Updated", MessageBoxButtons.OK, MessageBoxIcon.Information);
// now update/REFRESH the database so it shows the new record
GetProjectsDataset();
GetNotesDataset();
// reset form controls
ResetFormControls();
}
else
{
MessageBox.Show("Please select a note to delete", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
else
{
}
}
private void searchProjectsButton_Click(object sender, EventArgs e)
{
SqlCommand cmd = new SqlCommand("SELECT * FROM sfProjects WHERE Project_ID= #Project_ID", con);
cmd.CommandType = CommandType.Text;
cmd.Parameters.AddWithValue("#Project_ID", searchProjectsTextBox.Text); // maps #Project_ID to the search projects textbox
con.Open();
cmd.ExecuteNonQuery();
con.Close();
DataTable dtS = new DataTable();
con.Open();
SqlDataReader sdr = cmd.ExecuteReader();
dtS.Load(sdr);
con.Close();
dataGridView.DataSource = dtS;
// Automatically resizes the columns to fit the data grid view
dataGridView.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.Fill;
dataGridView.AutoSizeRowsMode = DataGridViewAutoSizeRowsMode.None;
// reset form controls
ResetFormControls();
}
private void searchNotesButton_Click(object sender, EventArgs e)
{
SqlCommand cmd = new SqlCommand("SELECT * FROM sfNotes WHERE Project_ID= #Project_ID", con);
cmd.CommandType = CommandType.Text;
cmd.Parameters.AddWithValue("#Project_ID", searchNotesTextBox.Text); // maps #Project_ID to the search projects textbox
con.Open();
cmd.ExecuteNonQuery();
con.Close();
DataTable dtS = new DataTable();
con.Open();
SqlDataReader sdr = cmd.ExecuteReader();
dtS.Load(sdr);
con.Close();
notesDataGridView.DataSource = dtS;
// Automatically resizes the columns to fit the data grid view
notesDataGridView.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.Fill;
notesDataGridView.AutoSizeRowsMode = DataGridViewAutoSizeRowsMode.None;
// reset form controls
ResetFormControls();
}
}
}
This is the section that the error is happening:
// Filter the notes grid to only show notes for the row the user clicks
SqlCommand cmd = new SqlCommand("SELECT * FROM sfNotes WHERE Project_ID_Backend= #Project_ID_Backend", con);
cmd.CommandType = CommandType.Text;
cmd.Parameters.AddWithValue("#Project_ID_Backend", this.ProjectIDBackend);
con.Open();
cmd.ExecuteNonQuery();
con.Close();
SOLUTION: The problem was that I didn't "refresh" the database in SSMS after saving it.
Check the exception documentation: https://learn.microsoft.com/en-us/dotnet/api/system.data.sqlclient.sqlexception?view=dotnet-plat-ext-3.1
The exception that is thrown when SQL Server returns a warning or error.
And the message:
Gets a message that describes the current exception
So the exception indicates that the query was executed on the database and that message is what the database returned. This leads me to believe one of two things.
Wrong connection string
You have made the change on a database that is different from the one your application connected to. A dev or test instance that you have not updated yet
You hand a pending transaction
You have run the script within a transaction that you have not committed.
Open a management studio and connect to the database that your application connects to. Try to execute the query.
Also check the profile you are building/running the application. Maybe it's release and you have transformed the connection string
i wanna do a combobox for the classes , when i insert the type of class in it i want to selecteditem the row that was selected exmple: i chose second row then i insert to the database a 2
sql = "insert into etudiant (Nom, prenom, sexe,classess) " +
"values(#Nom, #prenom, #sexe,#classess)"/*+"class (nom_class)" + "values(#nom_class) "*/;
cmd = new NpgsqlCommand(sql, conn);
cmd = new NpgsqlCommand(sql, conn);
cmd.Parameters.AddWithValue("#nom", bunifuMaterialTextbox1.Text);
cmd.Parameters.AddWithValue("#prenom", bunifuMaterialTextbox2.Text);
cmd.Parameters.AddWithValue("#sexe", bunifuMaterialTextbox3.Text);
int id = comboBox1.SelectedIndex + 1;
cmd.Parameters.AddWithValue("#classess",Int32.Parse(comboBox1.SelectedItem.ToString()));//*/
//cmd.Parameters.AddWithValue("Num", bunifuMaterialTextbox6.Text);
//cmd.Parameters.AddWithValue("Classess", bunifuMaterialTextbox7.Text);
int result = cmd.ExecuteNonQuery();
i couldn't find a way to do it like that
i wanna find a way so i can insert to table classes int for the number of that row like the ID
For your question, you would like to achieve the current combobox selected index and insert
it into your database.
First, I want to mention that you should use comboBox1.SelectedIndex instead of comboBox1.SelectedItem.
Second, I use sqlconnection to complete the same operation, so you can modify the following code to apply to your code.
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
string connstr = #"";
SqlConnection connection = new SqlConnection(connstr);
connection.Open();
string sql = "insert into Example(Nom,Prenom,Sexe,Classess) values(#Nom,#Prenom,#Sexe,#Classess)";
SqlCommand command = new SqlCommand(sql, connection);
command.Parameters.AddWithValue("#Nom", textBox1.Text);
command.Parameters.AddWithValue("#Prenom", textBox2.Text);
command.Parameters.AddWithValue("#Sexe", textBox3.Text);
command.Parameters.AddWithValue("#Classess", comboBox1.SelectedIndex+1);
command.ExecuteNonQuery();
MessageBox.Show("add value successfully");
}
private void Form1_Load(object sender, EventArgs e)
{
comboBox1.Items.Add("class1");
comboBox1.Items.Add("class2");
comboBox1.Items.Add("class3");
comboBox1.Items.Add("class4");
}
}
Hello so i want to refresh my combobox after i add or delete data from it now if i add data it doesnt get refreshed i have to rerun the program to see the changes but i want to get it refresh in the time i add the data..
the code when i add data:
private void button5_Click(object sender, EventArgs e)
{
MySqlConnection dataConnection = new MySqlConnection();
dataConnection.ConnectionString = "datasource=localhost;port=3306;username=root;password=";
dataConnection.Open();
MySqlTransaction transakcija = dataConnection.BeginTransaction();
MySqlCommand dataCommand = new MySqlCommand();
dataCommand.Connection = dataConnection;
dataCommand.Transaction = transakcija;
try
{
dataCommand.CommandText = "Insert INTO filmi.film (film) VALUES ('" + this.tB_Dodaj.Text + "')";
dataCommand.CommandType = CommandType.Text;
dataCommand.ExecuteNonQuery();
transakcija.Commit();
MessageBox.Show("You added a new movie!");
}
catch (Exception eks)
{
transakcija.Rollback();
MessageBox.Show("Movie couldnt be added!!\n" + eks.Message);
}
finally
{
dataCommand.Connection.Close();
}
}
and with each insert the data gets displayed in the combobox but only when i rerun the program
this is how i fill combobox:
void Fillcombo()
{
string constring = "datasource=localhost;port=3306;username=root;password=";
string Query = "SELECT * FROM filmi.film ;";
MySqlConnection conDataBase = new MySqlConnection(constring);
MySqlCommand cmdDataBase = new MySqlCommand(Query, conDataBase);
MySqlDataReader myReader;
try
{
conDataBase.Open();
myReader = cmdDataBase.ExecuteReader();
while (myReader.Read())
{
string sName = myReader.GetString("film");
comboBox1.Items.Add(sName);
comboBox2.Items.Add(sName);
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
i have to rerun the program to see the changes but i want to get it
refresh in the time i add the data..
I suspect that you are calling the Fillcombo() method in Form_Load event handler.
if you want to update the combobox for every insert and delete operations in your table you need to call Fillcombo() immediatly after executing the command.
Try This:
int status = dataCommand.ExecuteNonQuery();
transakcija.Commit();
if(status > 0)
{
Fillcombo();
MessageBox.Show("You added a new movie!");
}
in your FillCombo clear the items before adding the new items to remove the duplicates.
comboBox1.Items.Clear(); //add this statetement before adding items
comboBox2.Items.Clear(); //add this statetement before adding items
while (myReader.Read())
{
string sName = myReader.GetString("film");
comboBox1.Items.Add(sName);
comboBox2.Items.Add(sName);
}
ADO.NET object works in a disconnected state, so, adding a record to your datatable doesn't automatically shows up in your combo. You need to call again FillCombo, (clearing the items already in combos, going again to the database to retrieve every record again, adding them to your comboboxes) or just simply adding the film to your already filled combos as a single item
Also pay attention to Sql Injection (use always a parameterized query)
private void button5_Click(object sender, EventArgs e)
{
string conString = "datasource=localhost;port=3306;username=root;password=";
string cmdText = "Insert INTO filmi.film (film) VALUES (#film)";
using(MySqlConnection dataConnection = new MySqlConnection(conString))
using(MySqlCommand dataCommand = new MySqlCommand(cmdText, dataConnection))
{
try
{
dataConnection.Open();
dataCommand.Parameters.AddWithValue("#film", this.tB_Dodaj.Text);
// If ExecuteNonQuery returns a value > 0 then your record has been inserted
// Just add the name of the film to the two combos
if(dataCommand.ExecuteNonQuery() > 0)
{
MessageBox.Show("You added a new movie!");
comboBox1.Items.Add(this.tB_Dodaj.Text);
comboBox2.Items.Add(this.tB_Dodaj.Text);
}
}
catch(Exception ex)
{
MessageBox.Show("Fail to add a new movie! " + ex.Message);
}
}
}
As a last note, watch carefully your fillcombo method. You don't close and dispose the connection.
I have two drop down lists that effect each over, for example if you choose UK in the first drop down the second drop down will be populated from the UK table, if you select Germany it will be populated via German table and so on. each table contains the same three columns Specie, Specie_Price and Stock. I would like to reduce the stock integer by 1 each time a specie is chose from the second list and a button click happens. I am lost on how to build a update statement to do this on the selection from the second drop down, I would appriciate any help at all. I will post code bellow to give you better understanding on what I mean.
code for first drop down list on page load (country selection)
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
MySqlCommand cd2 = new MySqlCommand("SELECT * FROM Country", cs);
cs.Open();
MySqlDataReader ddlCountry = cd2.ExecuteReader();
ddlcountry.DataSource = ddlCountry;
ddlcountry.DataValueField = "Country";
ddlcountry.DataTextField = "Country";
ddlcountry.DataBind();
cs.Close();
cs.Dispose();
}
}
Code that populates the drop down with the Specie from the country chosen
protected void ddlcountry_SelectedIndexChanged(object sender, EventArgs e)
{
if (ddlcountry.Text != string.Empty)
{
MySqlCommand cd = new MySqlCommand(string.Format("SELECT * FROM {0}_Animals",
ddlcountry.Text), cs);
cs.Open();
MySqlDataReader ddlSpecie = cd.ExecuteReader();
DdPetPist.DataSource = ddlSpecie;
DdPetPist.DataValueField = "Specie";
DdPetPist.DataTextField = "Specie";
DdPetPist.DataBind();
cs.Close();
cs.Dispose();
}
}
so the what I want is that when they have chose there country then the specie they click button and id decrements the Stock of the table chosen buy 1.
I hope some one can help, thank you.
!!UPDATE ANSWER!!
Got it working 100% in the end,
protected void Button3_Click(object sender, EventArgs e)
{
string selection_price = DdPetPist.SelectedValue;
var myquery = string.Format("UPDATE Animals SET Stock = Stock - 1 WHERE Specie ='{1}' and Country ='{0}'", ddlcountry.SelectedItem.ToString().Trim(), selection_price);
using (MySqlConnection c = new MySqlConnection(connection string here))
using (MySqlCommand cmd = new MySqlCommand(myquery, c))
{
c.Open();
cmd.ExecuteNonQuery();
c.Close();
}
}
First, hook up a button click event handler, and then in the handler do something like this:
var sql = string.Format(
"UPDATE {0}_Animals SET Stock = Stock - 1 WHERE Specie = #Specie",
ddlcountry.Text);
using (MySqlConnection c = new MySqlConnection(cString))
using (MySqlCommand cmd = new MySqlCommand(sql, c))
{
c.Open();
cmd.Parameters.AddWithValue("#Specie", specie);
cmd.ExecuteNonQuery();
}
where cString is the connection string and specie is the identifier. I'm not 100% sure where that comes from, but I think the drop down lists selected value.
I am using Microsoft SQL Server and Visual Studio-C# 2010 Ultimate.
I have a ListView and some items in it. I want to delete an item when I selected it and I clicked the button but I could not write the SqlCommandtext and I could not find the select event for ListView.
Deleting selected data from database using listview c#
private void btnlvdeleterow_Click(object sender, EventArgs e)
{
foreach (int i in Listview2.SelectedIndices)
{
string test = Listview2.Items[i].Text;
Listview2.Items.Remove(Listview2.Items[i]);
SQLiteCommand conn = new SQLiteCommand();
conn.Connection = DbClass1.GetConnection();
string del = "delete from UserData where UserName='" + test + "'";
int result=dbclass1.ExecuteAndReturn(del);
}
}
There is a SelectedIndex property available with the ListView. When you click the button, pass this index and then your Sql query will be something like
delete from Products where ProductID = 'obj.ID' where obj is obtained from listView.SelectedIndex
protected void listview1_ItemDeleting(object sender, ListViewDeleteEventArgs e)
{
//This retrieves the selected row
ListViewItem item= listview1.Items [e.ItemIndex];
// Fetch the control for ProductId using findControl
int productId=int.Parse((item.Findcontrol("ProductID") as TextBox).Text);
//then use this column value in your sqlcommand
using( SqlCommand cmd = new SqlCommand
("delete from Products where ProductID=#ProductId", connection ))
{
command.Parameters.Add(new SqlParameter("ProductId", productId));
//Then execute the query
}
}
try
{
for (int j = 0; j <= listView2.Items.Count - 1; j++)
{
string test = listView2.SelectedItems[j].SubItems[1].Text;
string MyConnection2 = "datasource=localhost;port=3306;username=root;password=root";
string Query = "delete from TABLE_NAME where COL_NAME='" + test + "'";
MySqlConnection MyConn2 = new MySqlConnection(MyConnection2);
MySqlCommand MyCommand2 = new MySqlCommand(Query, MyConn2);
MySqlDataReader MyReader2;
MyConn2.Open();
MyReader2 = MyCommand2.ExecuteReader();
while (MyReader2.Read())
{
}
MyConn2.Close();
MessageBox.Show("Data Deleted");
// txtCustomerName.Text = test;
//listView2.Items.Remove(listView2.Items[i]);
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
The Event you are looking for should be ListView.ItemSelectionChanged
where the eventArgs contains the selected Items