Populating TextBox based on ComBox, Insert into Database through TextBox - c#

I'm having troubles populating TextBoxes based on a ComboBox, Also insertion code won't work.
What should happen is, By selecting a customer from ComboBox, The details gets displayed on Text Boxes, And i can also add a customer to the ComboBox through the TextBoxes, Also there is a DataGridView displaying related info from another table based on my ComboBox selection but that's not the problem now.
Note:
I switched to Visual Studio 2012 recently, I'm assuming that's not a problem.
ComboBox exception:
An exception of type 'System.Data.SqlServerCe.SqlCeException' occurred in System.Data.SqlServerCe.dll but was not handled in user code.
Save button exception:
Input string was not in a correct format.
About the save button, The CustomerID is an Auto increment number, So i should be able to leave it's TextBox blank but it doesn't work when i do.
Table Structure:
Customers
CustomerID [int] [PK] [AutoNumber]
Name [nvarchar]
Phone1 [int]
Phone2 [int]
Address [nvarchar]
Notes [ntext]
Code:
private void FillCombo()
{
string code = "SELECT CustomerID, Name FROM Customers";
SqlCeDataAdapter da = new SqlCeDataAdapter(code, clsMain.con);
DataSet ds = new DataSet();
da.Fill(ds);
cBox1.DataSource = ds.Tables[0];
cBox1.DisplayMember = "Name";
cBox1.ValueMember = "CustomerID";
}
private void frmMain_Load(object sender, EventArgs e)
{
clsMain.con.Open();
FillCombo();
}
private void cBox1_SelectedIndexChanged(object sender, EventArgs e)
{
string code = "SELECT * FROM Customers WHERE CustomerID='" + cBox1.Text + "'";
SqlCeDataAdapter da = new SqlCeDataAdapter(code, clsMain.con);
SqlCeCommandBuilder cmd = new SqlCeCommandBuilder(da);
DataSet ds = new DataSet();
da.Fill(ds);
if (cBox1.SelectedIndex > 0)
{
txt1.Text = ds.Tables[0].Rows[0]["CustomerID"].ToString();
txt2.Text = ds.Tables[0].Rows[0]["Name"].ToString();
txt3.Text = ds.Tables[0].Rows[0]["Phone1"].ToString();
txt4.Text = ds.Tables[0].Rows[0]["Phone2"].ToString();
txt5.Text = ds.Tables[0].Rows[0]["Address"].ToString();
txt6.Text = ds.Tables[0].Rows[0]["Notes"].ToString();
}
}
private void stripSave_Click(object sender, EventArgs e)
{
string code = "INSERT INTO Customers VALUES (#CustomerID, #Name, #Phone1, #Phone2, #Address, #Notes)";
SqlCeCommand cmd = new SqlCeCommand(code, clsMain.con);
cmd.Parameters.AddWithValue("#CustomerID", (txt1.Text); //Tried Parse and Convert.
cmd.Parameters.AddWithValue("#Name", txt2.Text);
cmd.Parameters.AddWithValue("#Phone1", txt3.Text);
cmd.Parameters.AddWithValue("#Phone2", txt4.Text);
cmd.Parameters.AddWithValue("#Address", txt5.Text);
cmd.Parameters.AddWithValue("#Notes", txt6.Text);
cmd.ExecuteNonQuery();
MessageBox.Show("Data stored.");
}
Sorry if it's a long code, But i thought it would be easier to spot the problems this way.

It seems like CustomerID is integral value, So you need to change
cmd.Parameters.AddWithValue("#CustomerID", txt1.Text);
to
cmd.Parameters.AddWithValue("#CustomerID", Int32.Parse(txt1.Text));
as per PhoenixReborn
if CustomerID is an auto increment, why are you trying to save it to the database? Kind of defeats the purpose.
then you need to edit your query to
string code = "INSERT INTO Customers(name, phone1, phone2, address, notes) VALUES (#Name, #Phone1, #Phone2, #Address, #Notes)";
SqlCeCommand cmd = new SqlCeCommand(code, clsMain.con);
cmd.Parameters.AddWithValue("#Name", txt2.Text);
cmd.Parameters.AddWithValue("#Phone1", txt3.Text);
cmd.Parameters.AddWithValue("#Phone2", txt4.Text);
cmd.Parameters.AddWithValue("#Address", txt5.Text);
cmd.Parameters.AddWithValue("#Notes", txt6.Text);
cmd.ExecuteNonQuery();
MessageBox.Show("Data stored.");

Try this instead:
private void stripSave_Click(object sender, EventArgs e)
{
int id;
string code;
SqlCeCommand cmd;
/*
If textbox is empty or input is not integer, then take the next id from table.
Otherwise, id is set to input value.
*/
if (txt1.Text == String.Empty || !int.TryParse(txt1.Text, out id))
{
/*
Selects max id + 1
If the table is empty, the result will be null
and coalesce will return 0 for the first id number
*/
code = "SELECT COALESCE((SELECT MAX(CustomerID) + 1 FROM Customers), 0);";
cmd = new SqlCeCommand(code, clsMain.con);
id = (int)cmd.ExecuteScalar();
}
code = "INSERT INTO Customers VALUES (#CustomerID, #Name, #Phone1, #Phone2, #Address, #Notes);";
cmd = new SqlCeCommand(code, clsMain.con);
cmd.Parameters.AddWithValue("#CustomerID", id);
cmd.Parameters.AddWithValue("#Name", txt2.Text);
cmd.Parameters.AddWithValue("#Phone1", txt3.Text);
cmd.Parameters.AddWithValue("#Phone2", txt4.Text);
cmd.Parameters.AddWithValue("#Address", txt5.Text);
cmd.Parameters.AddWithValue("#Notes", txt6.Text);
cmd.ExecuteNonQuery();
MessageBox.Show("Data stored.");
}
By the way, an important note about your code: Prefer to connect to database everytime you execute a query and close it afterwards. What I mean is that instead of keeping connection open for all the execution time, use something like this:
try
{
clsMain.con.Open();
cmd.ExecuteNonQuery();
clsMain.con.Close();
}
catch (Exception ex)
{
if (clsMain.con.State != ConnectionState.Closed)
clsMain.con.Close();
MessageBox.Show(ex.Message);
}

Related

Eliminating an option from a ComboBox (2), based on the input of the first ComboBox (1) c#

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;
}

Fill textbox with an incremented value from access database in C#

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.

C# Search Using ComboBox and TextBox (Access Database)

(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();
}

How to check if a field in a table already exists?

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.

How to autofill a radio_button, a few combo_boxes, many text_boxes, and a calendar FROM a combo_box selection

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);

Categories

Resources