I have created a combobox with items.
Visually in my form the items texts will apear, and i want to change the values to numbers when i insert in the database.
example :
private void contact(){
TypeAdrCmBx.Items.Add("NPAI");
TypeAdrCmBx.Items.Add("Personnelle");
TypeAdrCmBx.Items.Add("Professionelle");
TypeAdrCmBx.Items.Add("Vacances"); }
this is my insert Query :
string Query2 = "INSERT INTO [dbo].[Adresses] ([Type] ,[Adresse0],[Adresse1],[Adresse2],[CPT],[Ville],[Pays]) VALUES ('" + this.TypeAdrCmBx.Text + "','" + this.AdrTxtBx0.Text + "','" + this.AdrTxtBx1.Text + "','" + this.AdrTxtBx2.Text + "','" + this.CptTxtBx.Text + "','" + this.VilleTxtBx.Text + "','" + this.PaysCmBx0.Text + "')";
in the database the combobox values are inserted as numbers :
"NPAI" = 1
"Personnelle" = 2
"Professionelle" = 3
"Vacances" = 4
On Database side solution,
You need to you 2 tables in database in order to do it. One table will hold strings and values like
X Table
ID Number Value
1 1 "NPAI"
2 2 "Personnelle"
3 3 "Professionelle"
4 4 "Vacances"
and other table you will only use the numbers.
When you want to read them, u will use left join.
On c# side solution.
You can basicly convert them with if,
string a="";
if (TypeAdrCmBx.Text.Equals("NPAI"))
a="1";
else if (TypeAdrCmBx.Text.Equals("Personnelle"))
a="2";
And then simply make the insertion with a.
Hope it helps.
Related
How can I insert data from a text field into a foreign key in the database. Basically, I have tables named Employee and Role, RoleId is a foreign key in Employee, but the role text field is a string.
I have this
String Query = "insert into EMPLOYEE (LastName,FirstName,Manager,RoleId,HireStatus) values('" + this.txtLName.Text + "','" + this.txtFName.Text + "','" + this.txtManager.Text + "','" + this.txtRoleId.Text + "','" + this.txtHireStatus.Text + "');";
Edited - I have this, but I cannot have select with the following string
string Query = "insert into EMPLOYEE(LastName,FirstName,RoleId,Manager,HireStatus) values('" + this.txtLName.Text + "','" + this.txtFName.Text + "','" + ( SELECT RoleId From Role WHERE Role.RoleId = this.txtRole.Text ) + "','" + this.txtManager.Text + "','" + this.cmbHireStatus.Text + "');";
I think you should do this:
String Query = "insert into EMPLOYEE (LastName,FirstName,Manager,RoleId,HireStatus) values('" + this.txtLName.Text + "','" + this.txtFName.Text + "','" + this.txtManager.Text + "','" + this.txtRoleId.Text + "','" + this.txtHireStatus.Text + "');";
If you are trying to add a new Employee assigned to an existing role, then a better design would be have a dropdown with all Roles populated instead of a textbox for user to enter.
The dropdown should get filled with all the Roles from Roles table. (map the SelectedValue attribute of the dropdown to - RoleId and SelectedText to RoleName).
When you submit the form, you will get the SelectedValue (RoleId) which you can directly send as part of the INSERT statement, i.e., dropDownRole.SelectedValue instead of txtRoleId.Text
Note: Your insert query seems to be a classic candidate for SQL Injection. I suggest you transform it to Parameterized query.
Update: Now that I came to know it is a Winforms application, adding more detailed snippets. Here is how you can do it in the Win Forms world (not as intuitive as web app world though :) ) and please bear with me, it has been years since I had written a winforms snippet.
Define your dropdown combo box like this -
cbxRole.DataSource = roles; // data from back end
cbxRole.Name = "Role";
cbxRole.DropDownStyle = ComboBoxStyle.DropDownList;
cbxRole.DisplayMember = "RoleName"; // should match the property name in your roles data table
cbxRole.ValueMember = "RoleId"; // should match the property name in your roles data table
cbxRole.SelectedItem = null;
cbxRole.SelectedText = "Select Role";
Observe the ValueMember and DisplayMember properties. DisplayMember tells what property in the roles data source to be used to display as the dropdown item text. ValueMember specifies the property to be used to identify each of the item behind the scenes.
When you submit the details, access the SelectedValue property to get the RoleId corresponding to the selected role name.
private void btnCreate_Click(object sender, EventArgs e)
{
var firstName = txtFirstName.Text;
var lastName = txtLastName.Text;
var roleId = (int)cbxRole.SelectedValue;
}
The SelectedValue property fetches the value of the column identified by the ValueMember property in the dropdown definition, which is the RoleId value. Now, you can send this 'roleId' variable's value to the insert query.
here is how it looks like when you submit -
here is quick sample UI -
So I have make an order management system I have use this code to insert my order in data.
xconn.Open();
MySqlCommand cmd = new MySqlCommand();
cmd.CommandText = "insert into tblOrder
(RegId,ItmId,quantity,Odrdate,Total) values ('" + label11.Text + "','" +
26 + "','" + txt26.Text + "','" + date + "','" + lbltotal.Text + "');";
cmd.Connection = xconn;
cmd.ExecuteNonQuery();
xconn.Close();
So the order id in my table is auto increment but I want it to only increment after one order is complete.
Once I click total the odrid should increment so that next order gets a new id.
You simply can not insert a new row into a database table without a unique id, if the id is the primary key.
Why dont you introduce a new column „order_status“ in which you store the state of the current order?
Once I click total the odrid should increment so that next order gets
a new id.
What if a orderId is exist for example you click on 993 and you want 994 but it's already exists in database.
As Other suggested you can put a column that have information regarding your +1.
If you are using your current code in production your code can easily hacked using SQL-Injection be careful.
I am using c# winform, When the users input something in State field I want to look up that value in another table and find that code. I have commented the line below on what I have tried but that has not worked
MySqlCommand cmdDatabase = new MySqlCommand(" update `STUDENT REGISTER` INNER JOIN `States` ON `STUDENT REGISTER`.`State` = `States`.`State Code` set " +
"`first Name`='" + cboStudentFirstName.Text.Trim() + "'," +
"`Surname`='" + cboStudentSurname.Text.Trim() + "'," +
//if the person selects inputs VIC on this table I want it to look up that value in a table called states and bring me back the code for that state
"STUDENT REGISTER.State= States.State Code," +
I have below code:
query = "insert into tblB2B_OrderStatusTopStillInRB (LSRNbr, ShipName, Units, DroppedInRB, EPT, Status, OnTimeStatus, ShipVia, DroppedInRB_Order, RealEPT) ";
query += "values ('"
+ ListOrdStatusTopInRB[i].LSRNbr + "','"
+ ListOrdStatusTopInRB[i].ShipName + "',"
+ ListOrdStatusTopInRB[i].Units + ",'"
+ ListOrdStatusTopInRB[i].DroppedInRB + "','"
+ ListOrdStatusTopInRB[i].EPT + "','"
+ ListOrdStatusTopInRB[i].Status + "','"
+ ListOrdStatusTopInRB[i].OnTimeStatus + "','"
+ ListOrdStatusTopInRB[i].ShipVia + "','"
+ ListOrdStatusTopInRB[i].DroppedInRB_Order + "','"
+ ListOrdStatusTopInRB[i].RealEPT + "')";
cmd.CommandText = query;
cmd.ExecuteNonQuery();
And I just realized, that when the ShipName has a value with a single quotation mark, is causing an error in the insert statement, for instance: int'l Transp.
Is there any way to fix that, without removing the single quotation mark from the string?
I was trying using the following but didn't work:
cmd.CommandText = #query
+ #ListOrdStatusTopInRB[i].ShipName + "',"
Any ideas?
Is there any way to fix that, without removing the single quotation mark from the string?
Yes - use parameterized SQL instead. You should never use variable values directly in your SQL like this. It can allow SQL injection attacks, cause conversion oddities, and generally make the SQL more confusing to read.
See the documentation for SqlCommand.Parameters for an example of parameterized SQL.
Basically, the idea is that your SQL includes references to parameters, e.g.
INSERT INTO SomeTable(Foo, Bar) VALUES (#Foo, #Bar)
and then you specify the values for #Foo and #Bar separately. The values then aren't part of the SQL itself, so it doesn't matter whether or not they contain characters which would have special meaning within the SQL.
I m trying to save the date to mysql from jquery *DatePicker* from C#
string datetime = txtDate.Text + " " + time;//05/11/2011 5:30 pm
string getSQL1 =
"INSERT into tblconcertdetail
(Address, City, Pincode, Country, Concert_Date)
VALUES ('" + addr + "','" + txtCCity.Text + "','" + txtCpincode.Text + "','" +
ddlCCountry.SelectedItem.Text + "','" + Convert.DateTime(datetime) + "')";
Here getsql1 shows me the date field filled but in database it stores 0000-00-00 00:00 value.
I m not getting why it is so.
I also try convert.ToString(datetime) to.
As mentioned in comments, you have to use parameters for 2 reasons:
Prevent SQL Injections.
Handle data type conversions. In your case, handling the .NET DateTime type to its equivalent value in database.