In my project i have a countries combobox (PaysCmBx0) that is filled from countries database table [Pays] column [pays], what i want to do is when i select a country in the combobox it insert the Alpha country code token from the Alpha country code column [Alpha2] in another table (exemple : United-states = US).
so when i select a country from the combobox it does nothing it's intserting the same value.
My table look like this:
[Aplha2] [Pays]
GB United Kingdom
IM Isle of Man
TZ United Republic Of Tanzania
US United States
BF Burkina Faso
UY Uruguay
UZ Uzbekistan
here's my code :
void Fillcombo()
{
string Query = "SELECT * FROM Pays";
SqlCommand cmd = new SqlCommand(Query, con);
SqlDataReader myRead;
try
{
con.Open();
myRead = cmd.ExecuteReader();
while (myRead.Read())
{
string sName = myRead["Pays"].ToString();
PaysCmBx0.Items.Add(sName);
}
con.Close();
}
catch (Exception exc)
{
MessageBox.Show(exc.Message);
}
}
private void AddBtn_Click(object sender, EventArgs e)
{
try
{
string Query = "INSERT INTO [dbo].[Adresses] ([idParent],[Type] ,[Adresse0],[Adresse1],[Adresse2],[CPT],[Ville],[Pays]) VALUES ('"+Contact.idContact+"','" + TypeAdrCmBx.Text+ "','" + this.AdrTxtBx0.Text + "','" + this.AdrTxtBx1.Text + "','" + this.AdrTxtBx2.Text + "','" + this.CptTxtBx.Text + "','" + this.VilleTxtBx.Text + "','" + this.PaysCmBx0.Text + "')";
SqlCommand cmd = new SqlCommand(Query, con);
con.Open();
SqlDataReader Read;
try
{
Read = cmd.ExecuteReader();
}
catch (Exception exc)
{
MessageBox.Show(exc.Message);
}
con.Close();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
private void PaysCmBx0_SelectedIndexChanged(object sender, EventArgs e)
{
string Query1 = "SELECT * FROM Pays WHERE Pays='" + PaysCmBx0.Text + "'";
SqlCommand cmd1 = new SqlCommand(Query1, con);
SqlDataReader myRead;
try
{
con.Open();
myRead = cmd1.ExecuteReader();
while (myRead.Read())
{
string Code_Pays = myRead["Alpha2"].ToString();
PaysCmBx0.SelectedIndex.Equals(Code_Pays);
}
con.Close();
}
catch (Exception exc)
{
MessageBox.Show(exc.Message);
}
}
thanks every one i fund a solutions for this :
i create a function that gets the country code corresponding to what's selected in the combobox:
private string get_code_pays(string nom_pays)
{
string Query1 = "SELECT * FROM Pays WHERE Pays='" + PaysCmBx0.Text + "'";
string Code_Pays="";
SqlCommand cmd1 = new SqlCommand(Query1, con);
SqlDataReader myRead;
try
{
con.Open();
myRead = cmd1.ExecuteReader();
while (myRead.Read())
{
Code_Pays = myRead["Alpha2"].ToString();
PaysCmBx0.SelectedIndex.Equals(Code_Pays);
}
con.Close();
}
catch (Exception exc)
{
MessageBox.Show(exc.Message);
}
return Code_Pays;
}
and then call my funtion with the parameter in my insert:
string Query = "INSERT INTO [dbo].[Adresses] ([idParent],[Type] ,[Adresse0],[Adresse1],[Adresse2],[CPT],[Ville],[Pays]) VALUES ('"+Contact.idContact+"','" + A + "','" + this.AdrTxtBx0.Text + "','" + this.AdrTxtBx1.Text + "','" + this.AdrTxtBx2.Text + "','" + this.CptTxtBx.Text + "','" + this.VilleTxtBx.Text + "','" + get_code_pays( this.PaysCmBx0.Text) + "')";
Related
Form
Database
I want to make an employee Check in and Out form the check in part is done perfectly.
But for check out the update query allows to edit pre-entered values to change, I don't want already entered values to be able to change afterwards, and only enter Out_time to free cells.
Below is my code:
private void out_btn_Click(object sender, EventArgs e)
{
try
{
con.Open();
OleDbCommand cmd = con.CreateCommand();
cmd.CommandType = CommandType.Text;
cmd.CommandText = "update Daily_emp_track set Out_Time='" + time1.Text + "' where Emp_ID=" + id_txt.Text + " ";
cmd.ExecuteNonQuery();
con.Close();
MessageBox.Show("You are out");
}
catch (Exception ex)
{
MessageBox.Show("Entered ID not valid ");
con.Close();
}
}
To prevent the entered value from being changed again and get Out_Time by system instead of inputting manually, you could refer to the following code:
private void out_btn_Click(object sender, EventArgs e)
{
var time = DateTime.Now;
string time1;
if (time.Hour > 12)
{
time1 = time.Hour - 12 + ":" + time.Minute + " PM";
}
else
{
time1 = time.Hour + ":" + time.Minute + " AM";
}
try
{
string OutTime;
con.Open();
OleDbCommand cmd1 = con.CreateCommand();
cmd1.CommandType = CommandType.Text;
cmd1.CommandText = "SELECT Out_Time FROM Daily_emp_track WHERE Emp_ID='" + id_txt.Text + "'";
OleDbDataReader reader = cmd1.ExecuteReader();
while (reader.Read())
{
OutTime = reader["Out_Time"].ToString();
if (OutTime != "")
{
MessageBox.Show("Out Time has submitted");
}
else
{
OleDbCommand cmd = con.CreateCommand();
cmd.CommandType = CommandType.Text;
cmd.CommandText = "UPDATE Daily_emp_track SET Out_Time='" + time1 + "' WHERE Emp_ID='" + id_txt.Text + "'";
cmd.ExecuteNonQuery();
MessageBox.Show("You are out");
}
}
}
catch (Exception ex)
{
MessageBox.Show("Entered ID not valid ");
}
finally
{
con.Close();
}
}
I'm developing software in which I have a datagridview in wpf in which I have successfully done with inserting the values through fields in datagridview when clicked on insert button. But when I'm clicking on update I'm getting following exception .Find the screenshot of error below:
https://imgur.com/a/CV3n77K
The code that have been tried by myself is below :
public partial class Machine : Window
{
SqlConnection conn = new SqlConnection(#"Data Source=.\SQLEXPRESS;AttachDbFilename=D:\ATS\ATS Data Management System\ATS Data Management System\ATSDataManagementsystemDB.mdf;Integrated Security=True;User Instance=True");
public Machine()
{
InitializeComponent();
MaxHeight = SystemParameters.MaximizedPrimaryScreenHeight;
MaxWidth = SystemParameters.MaximizedPrimaryScreenWidth;
BindMyData();
}
public void BindMyData()
{
try
{
conn.Open();
SqlCommand comm = new SqlCommand("SELECT * FROM tblmachines", conn);
DataSet ds = new DataSet();
SqlDataAdapter da = new SqlDataAdapter(comm);
da.Fill(ds);
gridmachine.ItemsSource = ds.Tables[0].DefaultView;
}
catch (Exception ex)
{
MessageBox.Show(ex.Message.ToString());
}
finally
{
conn.Close();
}
}
private void btninsert_Click(object sender, RoutedEventArgs e)
{
try
{
conn.Open();
SqlCommand comm = new SqlCommand("INSERT INTO tblmachines VALUES('" + txtid.Text + "','" + txtsalesdate.Text + "','" + txtname.Text + "','" + txtpartname.Text + "','" + txtprice.Text + "','" + txtquantity.Text + "','" + txttotalamount.Text + "','" + paidpending.Text + "','" + txtpaidamount.Text + "','" + txtpendingamount.Text + "','" + txtcreditamountpaid.Text + "','" + txtpaiddate.Text + "','" + txtpaymentmode.Text + "')", conn);
comm.ExecuteNonQuery();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message.ToString());
}
finally
{
conn.Close();
BindMyData();
}
}
private void btnupdate_Click(object sender, RoutedEventArgs e)
{
try
{
conn.Open();
SqlCommand comm = new SqlCommand("UPDATE tblmachines SET SalesDate='" +txtsalesdate.Text+ "',Name='" +txtname.Text+"',Part Name='"+txtpartname.Text+"',Price="+txtprice.Text+",Quantity="+txtquantity.Text+",Total Amount="+txttotalamount.Text+",PaymentStatus='"+paidpending.Text+"',Paid Amount="+txtpaidamount.Text+",Pending Amount="+txtpendingamount.Text+",Credit Amount Paid="+txtcreditamountpaid.Text+",Paid Date='"+txtpaiddate.Text+"',Payment Mode='"+txtpaymentmode.Text+"'WHERE Id=" + txtid.Text + "", conn);
comm.ExecuteNonQuery();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message.ToString());
}
finally
{
conn.Close();
BindMyData();
}
}
}
}
I want the data to get updated and show up in data grid view but its not happening.
check your Part Name,Paid Amount, Pending Amount and Credit Amount Paid column, i think the error is the column name
SqlCommand comm = new SqlCommand("UPDATE tblmachines SET SalesDate='" +txtsalesdate.Text+ "',Name='" +txtname.Text+"',Part Name='"+txtpartname.Text+"',Price="+txtprice.Text+",Quantity="+txtquantity.Text+",Total Amount="+txttotalamount.Text+",PaymentStatus='"+paidpending.Text+"',Paid Amount="+txtpaidamount.Text+",Pending Amount="+txtpendingamount.Text+",Credit Amount Paid="+txtcreditamountpaid.Text+",Paid Date='"+txtpaiddate.Text+"',Payment Mode='"+txtpaymentmode.Text+"'WHERE Id=" + txtid.Text + "", conn);
You should also add space in the WHERE
Show your table structure
protected void btnSubmit_Click(object sender, EventArgs e)
{
string db = DropDownList1.SelectedItem.Value + "-" + DropDownList2.SelectedItem.Value + "-" + DropDownList3.SelectedItem.Value;
SqlConnection con = new SqlConnection("data source=BAN095\\SQLEXPRESS; database=Reg-DB; integrated security=SSPI");
SqlCommand cmd = new SqlCommand("select EmailID from Reg where EmailID='" + txtEmail.Text + "'", con);
con.Open();
Int32 count = (Int32)cmd.ExecuteScalar();
if (count==0)
{
Response.Write("email already Exists");
Response.End();
}
else
{
cmd.CommandText = "insert into Reg(FirstName,LastName,EmailID,PhoneNum,Gender,DOB)values('" + txtFirstName.Text + "','" + txtLastName.Text + "','" + txtEmail.Text + "','" + txtMobile.Text + "','" + RdoGender.SelectedItem.Value + "','" + db + "')";
cmd.Connection = con;
cmd.ExecuteNonQuery();
con.Close();
}
}
Please help me with this. And also for errors like use new keyword to create an object instance that I’m getting.
Put a unique index on EmailID, then perform just the insert and catch for SqlExceptions and check if exception.Number == 2601
Note: Use using statements to ensure that IDisposables will be disposed and use parameterized commands!
protected void btnSubmit_Click(object sender, EventArgs e)
{
string db = DropDownList1.SelectedItem.Value + "-" + DropDownList2.SelectedItem.Value + "-" + DropDownList3.SelectedItem.Value;
using(SqlConnection con = new SqlConnection("data source=BAN095\\SQLEXPRESS; database=Reg-DB; integrated security=SSPI"))
{
con.Open();
using (SqlCommand cmd = new SqlCommand("insert into Reg(FirstName,LastName,EmailID,PhoneNum,Gender,DOB)values(#FirstName,#LastName,#Email,#Mobile,#Gender,#Db)", con))
{
cmd.Parameters.AddWithValue("#FirstName", txtFirstName.Text);
//Do the same with other parameters
try
{
cmd.ExecuteNonQuery();
}
catch (SqlException ex)
{
if (ex.Number == 2601) // If instead of unique index, you have a unique constraint/primary key, check for ex.number==2627
{
// Duplicate key! Do whatever you want
}
}
}
}
}
When i want to insert a row into my MySql database 4 rows will be inserted instead of 1. Could you help me?
MySqlConnection con = new MySqlConnection(cs);
string Query = "Insert Into csokolade (márka,ár,darab) values('" + this.Marka_Textbox.Text + "','" + this.Ar_Textbox.Text + "','" + this.Darab_Textbox.Text + "')";
MySqlCommand com = new MySqlCommand(Query, con);
com.ExecuteNonQuery();
EDIT: Here is the part of the code that has to insert the row:
try
{
MySqlConnection con = new MySqlConnection(cs);
con.Open();
int a = 0;
string q = "select count(*) from csokolade where márka='" + this.Marka_Textbox.Text + "';";
MySqlCommand com = new MySqlCommand(q, con);
try
{
a = Convert.ToInt32(com.ExecuteScalar());
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
if (a == 0)
{
string Query = "Insert Into csokolade (márka,ár,darab) values('" + this.Marka_Textbox.Text + "','" + this.Ar_Textbox.Text + "','" + this.Darab_Textbox.Text + "')";
com = new MySqlCommand(Query, con);
com.ExecuteNonQuery();
}
else
{
MessageBox.Show("Ez a rekord már létezik!");
return;
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
I am inserting data to access 2000-2003 file format database using C#. When I had a database with 2 fields the query works fine, but when there are more fields its is not working.
I have identical code for both and I am not able to find the problem.
using System.Data.OleDb; // By using this namespace I can connect to the Access Database.
namespace WindowsFormsApplication1
{
public partial class Form1 : Form
{
private OleDbConnection myconn;
public Form1()
{
InitializeComponent();
myconn = new OleDbConnection(#"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\Users\leelakrishnan\Desktop\NewManageContacts.mdb");
}
private void Form1_Load(object sender, EventArgs e)
{
// TODO: This line of code loads data into the 'newManageContactsDataSet.Contacts' table. You can move, or remove it, as needed.
// this.contactsTableAdapter.Fill(this.newManageContactsDataSet.Contacts);
// TODO: This line of code loads data into the 'newManageContactsDataSet.Contacts' table. You can move, or remove it, as needed.
this.contactsTableAdapter.Fill(this.newManageContactsDataSet.Contacts);
}
private void button1_Click(object sender, EventArgs e)
{
OleDbCommand cmd = new OleDbCommand();
cmd.CommandType = CommandType.Text;
// string query = "insert into Contacts (fname,lname,llnum,mobnum,e-mail,street,city,country) values ('" + textBox1.Text + "','" + textBox2.Text + "','" + textBox3.Text + "','" + textBox4.Text + "','" + textBox5.Text + "','" + textBox6.Text + "','" + textBox7.Text + "','" + textBox8.Text + "')";
cmd.CommandText = #"insert into Contacts (fname,lname,llnum,mobnum,e-mail,street,city,country) values ('" + textBox1.Text + "','" + textBox2.Text + "','" + textBox3.Text + "','" + textBox4.Text + "','" + textBox5.Text + "','" + textBox6.Text + "','" + textBox7.Text + "','" + textBox8.Text + "')";
cmd.Connection = myconn;
myconn.Open();
cmd.ExecuteNonQuery();
System.Windows.Forms.MessageBox.Show("User Account Succefully Created", "Caption", MessageBoxButtons.OKCancel, MessageBoxIcon.Information);
myconn.Close();
}
private void button2_Click(object sender, EventArgs e)
{
textBox1.Text = "";
textBox2.Text = "";
textBox3.Text = "";
textBox4.Text = "";
textBox5.Text = "";
textBox6.Text = "";
textBox7.Text = "";
textBox8.Text = "";
}
private void textBox1_TextChanged(object sender, EventArgs e)
{
}
}
}
This is the code for the table with just 2 fields
public partial class Form1 : Form
{
private OleDbConnection myCon;
public Form1()
{
InitializeComponent();
myCon = new OleDbConnection(#"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\Users\leelakrishnan\Desktop\Database1.mdb");
}
private void Form1_Load(object sender, EventArgs e)
{
// TODO: This line of code loads data into the 'database1DataSet.Table1' table. You can move, or remove it, as needed.
this.table1TableAdapter.Fill(this.database1DataSet.Table1);
}
private void button1_Click(object sender, EventArgs e)
{
OleDbCommand cmd = new OleDbCommand();
cmd.CommandType = CommandType.Text;
cmd.CommandText = "insert into Table1 (name,fname) values ('" + textBox1.Text + "','" + textBox2.Text + "')";
cmd.Connection = myCon;
myCon.Open();
cmd.ExecuteNonQuery();
System.Windows.Forms.MessageBox.Show("User Account Succefully Created", "Caption", MessageBoxButtons.OKCancel, MessageBoxIcon.Information);
myCon.Close();
}
private void button2_Click(object sender, EventArgs e)
{
textBox1.Text = "";
textBox2.Text = "";
}
}
The extra fields you are trying to insert probably have values that don't readily concatenate into a valid SQL statement. For instance:
string field1 = "meh";
string field2 = "whatever";
string field3 = "'Ahoy!' bellowed the sailor.";
var cmd = new SqlCommand(
"INSERT INTO blah (x, y, z) VALUES ('" + field1 + "', '" + field2 + "', '" + field3 + '")");
Imagine what the concatenated SQL will look like, given the above input.
Worse, imagine the SQL you'll be executing if someone types this into your form:
field3 = "Bobby'); DROP TABLE Users; -- ";
Use parameterised queries via cmd.Parameters.Add or AddRange (described here). The above example might be emended thus:
var cmd = new SqlCommand("INSERT INTO blah (x, y, z) VALUES (#x, #y, #z)");
cmd.Parameters.AddRange(new[] {
new SqlParameter("#x", field1),
new SqlParameter("#y", field2),
new SqlParameter("#z", field2)
});
This code for public:
OleDbConnection con = new OleDbConnection(#"Provider = Microsoft.Jet.OLEDB.4.0; Data Source = C:\Users\Mohammadhoseyn_mehri\Documents\Data.mdb");
This code for singup button:
try
{
createaccount();
else
{
MessageBox.Show("Please re-enter your password");
}
}
catch(Exception ex)
{
MessageBox.Show(ex.Message);
}
finally
{
MessageBox.Show("Data saved successfully...!");
con.Close();
}
This is the code for create account method:
OleDbDataAdapter adapter = new OleDbDataAdapter("SELECT * from Login", con);
con.Open();
String ticketno = textBox2.Text.ToString();
String Purchaseprice = textBox1.Text.ToString();
String my_query = $"INSERT INTO Login (username, pass) VALUES ('{ticketno}', '{Purchaseprice}')";
OleDbCommand cmd = new OleDbCommand(my_query, con);
cmd.ExecuteNonQuery();
If you are working with databases, then mostly take the help of try-catch block statement, which will help and guide you with your code. Here I am showing you that how to insert some values in database with a button click event.
private void button2_Click(object sender, EventArgs e)
{
System.Data.OleDb.OleDbConnection conn = new System.Data.OleDb.OleDbConnection();
conn.ConnectionString = #"Provider=Microsoft.ACE.OLEDB.12.0;" +
#"Data source= C:\Users\pir fahim shah\Documents\TravelAgency.accdb";
try
{
conn.Open();
String ticketno=textBox1.Text.ToString();
String Purchaseprice=textBox2.Text.ToString();
String sellprice=textBox3.Text.ToString();
String my_query = "INSERT INTO Table1(TicketNo,Sellprice,Purchaseprice)VALUES('"+ticketno+"','"+sellprice+"','"+Purchaseprice+"')";
OleDbCommand cmd = new OleDbCommand(my_query, conn);
cmd.ExecuteNonQuery();
MessageBox.Show("Data saved successfuly...!");
}
catch (Exception ex)
{
MessageBox.Show("Failed due to"+ex.Message);
}
finally
{
conn.Close();
}
private void btnSave_Click(object sender, EventArgs e)**
{
OleDbCommand cmd = new OleDbCommand();
cmd.CommandType = CommandType.Text;
cmd.CommandText = #"insert into Personal (P_name, P_add,P_Phone)VALUES('" + txtName.Text + "','" +txtAddress.Text + "','" + txtPhone.Text + "')";
cmd.Connection = con;
con.Open();
cmd.ExecuteNonQuery();
System.Windows.Forms.MessageBox.Show("Recrod Succefully Created");
con.Close();
txtName.Text = "";
txtAddress.Text = "";
txtPhone.Text = "";
}