I am creating an airline booking system and I have 2 combo boxes. The first is for Departure City and the second is for Arrival City. I want to be able to eliminate the choice in the first combo box from the second, as I don't want the same city to be able to be submitted as both the departure and arrival city. I am querying the city names from a database.
Here is my code:
public partial class main : Form
{
public main()
{
InitializeComponent();
string connectionString = #"Base Schema Name=cyanair;data source=C:\Users\Client 0819\source\repos\Cyanair\cyanair.db";
//Departure ComboBox
SQLiteConnection conn = new SQLiteConnection(connectionString);
try
{
conn.Open();
SQLiteCommand cmd = new SQLiteCommand();
cmd.Connection = conn;
cmd.CommandType = System.Data.CommandType.Text;
cmd.CommandText = "SELECT * FROM CyanairAirports";
SQLiteDataAdapter da = new SQLiteDataAdapter(cmd);
DataTable dt = new DataTable();
da.Fill(dt);
comboDeparture.DataSource = dt;
comboDeparture.ValueMember = "Descriptions";
comboDeparture.DisplayMember = "Descriptions";
conn.Close();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
//Arrival ComboBox
private void comboDeparture_DisplayMemberChanged(object sender, EventArgs e)
{
string connectionString = #"Base Schema Name=cyanair;data source=C:\Users\Client 0819\source\repos\Cyanair\cyanair.db";
SQLiteConnection conn = new SQLiteConnection(connectionString);
**String city = comboDeparture.DisplayMember;**
try
{
conn.Open();
SQLiteCommand cmd = new SQLiteCommand();
cmd.Connection = conn;
cmd.CommandType = System.Data.CommandType.Text;
cmd.CommandText = "SELECT * FROM CyanairAirports WHERE Descriptions IS NOT '" + comboDeparture.SelectedValue.ToString() + "'";
richTextBox1.Text = "SELECT * FROM CyanairAirports WHERE Descriptions IS NOT '" + comboDeparture.SelectedValue + "'";
SQLiteDataAdapter da = new SQLiteDataAdapter(cmd);
DataTable dt = new DataTable();
da.Fill(dt);
comboArrival.DataSource = dt;
comboArrival.ValueMember = "Descriptions";
comboArrival.DisplayMember = "Descriptions";
conn.Close();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
Thanks :)
It looks like you're handling the DisplayMemberChanged event on comboDeparture, and trying to update the values of comboArrival in that handler. However, DisplayMemberChanged only triggers when the DisplayMember property changes.
DisplayMember only tells the control which property to display on a data bound control. It isn't tied to the index or value selected in the ComboBox. So, the only time the code to populate comboArrival runs is in the constructor when you set comboDepartarture.DisplayMember. Instead, handle either ComboBox.SelectedIndexChanged or ComboBox.SelectedValueChanged and set the items of comboArrival.
A few other important things to note about your code.
First, you should use a parameterized query when running Sql Statements, rather than concatenating strings. Concatenating strings as you're doing opens you up to SQL Injection Attacks. I'm not familiar with SqlLite and can't provide you with an example of how to modify your code, but perhaps this question can help.
Second, you don't need to re-run the query every time you change the selected value in comboDeparture. Just add comboArrival's data source as a field on the Form and you can filter it. For example...
public partial class main : Form
{
// Your constructors...
private void comboDepartures_SelectedIndexChanged(object sender, EventArgs e)
{
if (_arrivalsDataSource == null)
{
_arrivalsDataSource = new System.Data.DataTable();
// Load _arrivalsDataSource from the database, basically how you're doing it now.
comboArrival.DataSource = _arrivalsDataSource.DefaultView;
comboArrival.DisplayMember = "Descriptions"
comboArribal.ValueMember = "Descriptions"
}
if (comboDeparture.SelectedIndex == -1)
{
_arrivalsDataSource.DefaultView.RowFilter = null; // Clear the filter.
}
else
{
// Set the filter.
_arrivalsDataSource.DefaultView.RowFilter = $"Description <> '{comboDeparture.SelectedValue}'";
}
}
private System.Data.DataTable _arrivalsDataSource = null;
}
I created a C# application to query and insert a product database. However I am here with a small doubt and if anyone can help me i thank you right away.
The following is:
I have a form to insert data into the database created in MS Access 2007, with the values of reference, sale number, client code, client name, quantity and position number in archive;
Here is my code until the moment:
private void btn_save_Click(object sender, EventArgs e)
{
OleDbConnection con = new OleDbConnection(#"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=product.accdb");
OleDbCommand check_sn = new OleDbCommand("SELECT COUNT(*) FROM [product] WHERE ([sn] = #sn)", con);
OleDbCommand check_reference = new OleDbCommand("SELECT COUNT(*) FROM [product] WHERE ([reference] = #ref)", con);
OleDbCommand check_number = new OleDbCommand("SELECT COUNT(*) FROM [product] WHERE ([number] = #num)", con);
con.Open();
check_reference.Parameters.AddWithValue("#ref", textBox_ref.Text);
check_sn.Parameters.AddWithValue("#sn", textBox_sn.Text);
check_number.Parameters.AddWithValue("#num", textBox_num.Text);
int refExist = (int)check_reference.ExecuteScalar();
int SNExist = (int)check_sn.ExecuteScalar();
int numExist = (int)check_number.ExecuteScalar();
if (refExist > 0)
{
MessageBox.Show("A product with this reference already exists....!");
}
else if (SNExist> 0)
{
MessageBox.Show("A product with this sale number already exists....!");
}
else if (numExist > 0)
{
MessageBox.Show("A product with this archive number already exists....!");
}
else
{
try
{
String reference = textBox_ref.Text.ToString();
String sn = textBox_ov.Text.ToString();
String cod_client = textBox_cod.Text.ToString();
String client = textBox_cliente.Text.ToString();
String qtd = textBox_qtd.Text.ToString();
String number = textBox_num.Text.ToString(); //This will be the incremented number
String my_query = "INSERT INTO product(reference,sn,cod_client,client,qtd,number)VALUES('" + reference + "','" + sn + "','" + cod_client + "','" + client + "','" + qtd + "','" + number + "')";
OleDbCommand cmd = new OleDbCommand(my_query, con);
cmd.ExecuteNonQuery();
MessageBox.Show("Data saved successfully...!");
}
catch (Exception ex)
{
MessageBox.Show("Failed due to" + ex.Message);
}
finally
{
con.Close();
}
cleanTextBoxes(this.Controls);
}
}
private void search_btn_Click(object sender, EventArgs e)
{
Form search = new Form_search();
search.Show();
this.Hide();
}
}
}
How can i make it so that instead of manually entering the position number in archive in the textbox it can be automatically filled with the new position in archive. For example, my last product inserted has the position 50 in archive, the new one will automatically be number 51 and so on ... and this number should appear automatically in the textbox so that the user knows what is the number of the new registered product.
Thank you,
Ok i have tried this and works but how i do now to increment this value +1?
OleDbConnection con = new OleDbConnection(#"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=Aneis_Calibre.accdb");
con.Open();
OleDbDataReader myReader = null;
OleDbCommand number = new OleDbCommand("SELECT TOP 1 [number] FROM product Order by [number] desc", con);
myReader = number.ExecuteReader();
while (myReader.Read())
{
textBox_num.Text = (myReader["number"].ToString());
}
con.Close();
Inside your query, you would want to do something along these lines.
INSERT ...
OUTPUT inserted.identity_column
VALUES (...)
That will return a row with a value for the id. The identity column in SQL will always increment automatically for you. Which would alleviate your approach where you grab the last record and do:
int.TryParse(reader["..."]?.ToString(), out int id);
textbox.Text = id++;
By using the scalar, or reader though I would recommend scalar if you return a single column with a modified SQL query would result in the exact newly inserted id.
(First of all...... Sorry to my english :D)
I already post my problem here c# Search using ComboBox and Textbox .. no one solved my problem but I used their codes to simplify my codes.
When I started the program the DataGridView looks so normal.. I choose a field in ComboBox and type in TextBox.. the results showed but the problem is.... their's another column that added to the DataGridView and it's empty... I want you to help me to remove that column
Here's the image (I am new here in stackoverflow.. I dont have enough reputation to post images)
public void searchData()
{
string sql = "Select ID,Quantity,Unit,ItemCode,ItemName,Cbm,TotalCbm from Inventory Order By ID asc;";
cmd = new OleDbCommand(sql, con);
try
{
con.Open();
string value = cboFields.Text;
cmd.CommandText = String.Format(
#"Select ID,
Quantity,Unit,ItemCode,ItemName,Cbm,TotalCbm
from Inventory
where {0} like #searchKey Order By ID asc;", value);
cmd.Parameters.AddWithValue("#searchKey", txtSearch.Text.ToString() + "%");
OleDbDataAdapter adp= new OleDbDataAdapter(cmd);
//DataSet ds = new DataSet();
//adp.Fill(ds);
//DGVinventory.DataSource = ds;
DataTable dt = new DataTable();
adp.Fill(dt);
DGVinventory.DataSource = dt;
con.Close();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
con.Close();
}
}
private void txtSearch_TextChanged(object sender, EventArgs e)
{
searchData();
}
my question is very simple:
i have a SQL Table with a column name 'lastname' with fields lastname1,lastname2,lastname3...
In my c# code, i have a method that inserts in the table a row only if the field of the column lastname is not present in the table. This method in input has lastname, so for my INSERT is a parameter.
How can i compare and conseguently check if the field lastname is already in table?
Thanks
You should always use unique constraints in the table if a field must be unique. On that way you prevent duplicates always, even if the input was directly from SSMS or another application.
Then the easiest would be to handle the sql-exception that is raised according to it's number.
....
try
{
int inserted = cmd.ExecuteNonQuery();
} catch (SqlException ex)
{
if (ex.Number == 2601)
{
// show meaningful error message
MessageBox.Show("Cannot insert duplicate key row in object");
}
else
throw;
}
....
This SQL will insert a new record only if the value isn't already in the table:
INSERT INTO Your_Table ( LastName )
SELECT #NewLastName
WHERE NOT EXISTS( SELECT * FROM Your_Table WHERE LastName = #NewLastName )
There are two option one is from sql side another way is from code behind.
unfortunately you can't change your sql code i agree with #David.
from code behind you have to do something like this.
First you have to select all the data from your table and check that data. something like this.
SqlConnection con = new SqlConnection();
SqlCommand cmd = new SqlCommand();
cmd.Connection = con; //Your connection string"
cmd.CommandText = "Select * from table1"; // your query
cmd.CommandType = CommandType.Text;
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
da.Fill(ds);
DataTable dt = new DataTable();
dt = ds.Tables[0];
int count=0;
for (int i = 0; i > dt.Rows.Count; i++)
{
if (Convert.ToString(dt.Rows[i]["LastName"]) == Lastname)
{
count++;
}
}
if (count > 0)
{
//insert code for data
}
else
{
var script = "alert('"+ Lastname + "already exist.');";
ClientScript.RegisterStartupScript(typeof(Page), "Alert", script, true);
// or you can use here your Update statement
}
May this will help you and you can understand.
I am creating a tool that will allow a Human Resource employee to input various information about a new employee into an access database(for academic purposes). So far I have the layout set-up (as you will be able to see shortly), validation is in a place, and a dataGridView gets populated by using an Access Database I created. Then I have 3 buttons, Submit (Insert), Update and Delete.
PS: I know that the table I am trying to update is huge, but that's what our team decided to do.
Image of my layout:
Human Resource employee tool
The submit and delete works, BUT the update only works if all of the fields are filled with data. The code I wrote tries to update all the fields WHERE the EMPLOYEE_ID equals the value that's selected on the combo_box, so if I try to update only one field I get an error saying "No value given for one or more required parameters". I think that by auto-filling all the field on the left when a value from a combo_box is selected will fix my problem. The thing is that I have no idea on how to accomplish this. Any help would be appreciate it!!
UPDATE STATEMENT.
private void cmdModify_Click(object sender, EventArgs e)
{
//Setting up Connection String
string connectionString = GetConnectionString();
string SqlString = "UPDATE Employee SET FIRST_NAME = #FirstName , LAST_NAME= #LastName, MIDDLE_NAME = #MiddleName, DATE_HIRED =#DateHired, WAGE_TYPE =#WageType, WAGE = #Wage, GENDER =#Gender, MARTIAL_STATUS =#MartialStatus, UNIT_NUMBER =#UnitNumber, STREET_NUMBER =#StreetNumber, STREET_NAME =#StreetName, CITY =#City, PROVINCE =#Province, POSTAL_CODE =#PostalCode, HOME_NUMBER =#HomeNumber, CELL_NUMBER =#CellNumber, JOB_TITTLE =#JobTittle, END_DATE=7/24/2013, DPT_NAME =#Department, NOTES =#Notes WHERE [EMPLOYEE_ID] = #EMPLOYEE_ID";
using (OleDbConnection conn = new OleDbConnection(connectionString))
{
using (OleDbCommand cmd = new OleDbCommand(SqlString, conn))
{
cmd.CommandType = CommandType.Text;
cmd.Parameters.AddWithValue("FirstName", txtFname.Text);
cmd.Parameters.AddWithValue("LastName", txtLname.Text);
cmd.Parameters.AddWithValue("MiddleName", txtMname.Text);
cmd.Parameters.AddWithValue("DateHired", dateTimePicker1.Text);
cmd.Parameters.AddWithValue("WageType", cmbType.SelectedItem);
cmd.Parameters.AddWithValue("Wage", txtWage.Text);
if (rbMale.Checked == true)
{
cmd.Parameters.AddWithValue("Gender", rbMale.Text);
}
else if (rbFemale.Checked == true)
{
cmd.Parameters.AddWithValue("Gender", rbFemale.Text);
}
cmd.Parameters.AddWithValue("MartialStatus", cmbStatus.SelectedItem);
cmd.Parameters.AddWithValue("UnitNumber", txtUnit.Text);
cmd.Parameters.AddWithValue("StreetNumber", txtStreetNo.Text);
cmd.Parameters.AddWithValue("StreetName", txtStreet.Text);
cmd.Parameters.AddWithValue("City", txtCity.Text);
cmd.Parameters.AddWithValue("Province", cmbState.SelectedItem);
cmd.Parameters.AddWithValue("PostalCode", txtPostal.Text);
cmd.Parameters.AddWithValue("HomeNumber", txtHphone.Text);
cmd.Parameters.AddWithValue("CellNumber", txtCphone.Text);
cmd.Parameters.AddWithValue("JobTittle", cmbJobTitle.SelectedItem);
cmd.Parameters.AddWithValue("Department", cmbDepartment.SelectedItem);
cmd.Parameters.AddWithValue("Notes", txtNotes.Text);
cmd.Parameters.AddWithValue("EMPLOYEE_ID", comboBox1.SelectedValue);
try
{
// openning a connection to the database / table
conn.Open();
// SQL commnd class
cmd.ExecuteNonQuery();
//Closing Database connection
conn.Close();
//Console.WriteLine("Data was added to the table !!!");
MessageBox.Show("Data was added to the table !!!");
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
//Console.WriteLine(ex.Message); // printing exception message to default output
}
}
}
Refresh();
clearText();
}
INSERT STATEMENT.
private void Insert_Data()
{
string connectionString = GetConnectionString();
string SqlString = "INSERT INTO Employee (FIRST_NAME, LAST_NAME, MIDDLE_NAME, DATE_HIRED, WAGE_TYPE, WAGE, GENDER, MARTIAL_STATUS,UNIT_NUMBER, STREET_NUMBER, STREET_NAME, CITY ,PROVINCE, POSTAL_CODE, HOME_NUMBER, CELL_NUMBER, JOB_TITTLE, END_DATE, DPT_NAME, NOTES) VALUES (#FirstName,#LastName,#MiddleName,#DateHired,#WageType,#Wage,#Gender,#MartialStatus,#UnitNumber,#StreetNumber,#StreetName,#City,#Province,#PostalCode,#HomeNumber,#CellNumber,#JobTittle,7/24/2013,#Department,#Notes)";
using (OleDbConnection conn = new OleDbConnection(connectionString))
{
using (OleDbCommand cmd = new OleDbCommand(SqlString, conn))
{
cmd.CommandType = CommandType.Text;
cmd.Parameters.AddWithValue("FirstName", txtFname.Text);
cmd.Parameters.AddWithValue("LastName", txtLname.Text);
cmd.Parameters.AddWithValue("MiddleName", txtMname.Text);
cmd.Parameters.AddWithValue("DateHired", dateTimePicker1.Text);
cmd.Parameters.AddWithValue("WageType", cmbType.SelectedItem);
cmd.Parameters.AddWithValue("Wage", txtWage.Text);
if (rbMale.Checked == true)
{
cmd.Parameters.AddWithValue("Gender",rbMale.Text);
}
else if (rbFemale.Checked == true)
{
cmd.Parameters.AddWithValue("Gender", rbFemale.Text);
}
cmd.Parameters.AddWithValue("MartialStatus", cmbStatus.SelectedItem);
cmd.Parameters.AddWithValue("UnitNumber", txtUnit.Text);
cmd.Parameters.AddWithValue("StreetNumber", txtStreetNo.Text);
cmd.Parameters.AddWithValue("StreetName", txtStreet.Text);
cmd.Parameters.AddWithValue("City", txtCity.Text);
cmd.Parameters.AddWithValue("Province", cmbState.SelectedItem);
cmd.Parameters.AddWithValue("PostalCode", txtPostal.Text);
cmd.Parameters.AddWithValue("HomeNumber", txtHphone.Text);
cmd.Parameters.AddWithValue("CellNumber", txtCphone.Text);
cmd.Parameters.AddWithValue("JobTittle", cmbJobTitle.SelectedItem);
cmd.Parameters.AddWithValue("Department", cmbDepartment.SelectedItem);
cmd.Parameters.AddWithValue("Notes", txtNotes.Text);
try
{
// openning a connection to the database / table
conn.Open();
// SQL commnd class
cmd.ExecuteNonQuery();
//Closing Database connection
conn.Close();
//Console.WriteLine("Data was added to the table !!!");
MessageBox.Show("Data was added to the table !!!");
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
//Console.WriteLine(ex.Message); // printing exception message to default output
}
}
}
Refresh();
clearText();
}
DELETE STATEMENT
private void cmdDelete_Click_1(object sender, EventArgs e)
{
//Setting up Connection String
string connectionString = GetConnectionString();
string SqlString = "DELETE * FROM Employee WHERE [EMPLOYEE_ID] = #EMPLOYEE_ID ";
using (OleDbConnection conn = new OleDbConnection(connectionString))
{
using (OleDbCommand cmd = new OleDbCommand(SqlString, conn))
{
cmd.CommandType = CommandType.Text;
cmd.Parameters.AddWithValue("EMPLOYEE_ID", comboBox1.SelectedValue);
try
{
// openning a connection to the database / table
conn.Open();
// SQL commnd class
cmd.ExecuteNonQuery();
//Closing Database connection
conn.Close();
//Console.WriteLine("Data was added to the table !!!");
MessageBox.Show("Data was deleted from the table !!!");
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
//Console.WriteLine(ex.Message); // printing exception message to default output
}
}
}
Refresh();
clearText();
}
You are getting this error because the AddWithValue method is adding null to the Parameters collection. What you need is for it to add DBNull instead.
cmd.Parameters.AddWithValue("FirstName", txtFname.Text ?? DBNull.Value);
Those SelectedItem values might cause you problems too if they are complex types:
cmd.Parameters.AddWithValue("Province", cmbState.SelectedItem);
You might have to specify a property on the instance to make it work
cmd.Parameters.AddWithValue("Province", cmbState.SelectedItem.MyIdProperty);