look up value from another sql table in c# winforms - c#

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," +

Related

How to sovle Query Issue throwing MySql.Data.MySqlClient.MySqlException

I am doing a project with C# and I have this error:
MySql.Data.MySqlClient.MySqlException (0x80004005): You have an error
in your SQL syntax; check the manual that corresponds to your MariaDB
server version for the right syntax to use near ' last_name= , email=
, phone= , address= WHERE id= 6' at line 1
I know this is a query error, but I tried many things and I don't see the issue.
My query is this:
cm = new MySqlCommand("UPDATE customers SET first_name= " + txtNombre.Text + "," + " last_name= " + txtApellidos.Text + "," + " email= " + txtEmail.Text + "," + " phone= " + txtTelefono.Text + "," + " address= " + txtDireccion.Text + " WHERE id= " + dgvClient.SelectedRows[0].Cells[0].Value.ToString() , con);
There should be single quotes around the text that you want to inject into the query, so it will look like this:
var query = "UPDATE customers SET first_name= '" + txtNombre.Text + "'";
This is the easiest solution but is advised against, mostly because of a possiblity for 'sql injection'. The easiest way to show this is by using the name O'Brian, because of the quote the database will think that the name is only O and then see it followed by Brian that it doesn't know what to do with and gives an error. Some people can use this to add other things to your query to cause harm to your database (like dropping tables or the whole database)
It is advised to use parameters, this solves this whole sql injection issue. Your code will look as follows:
cm = new MySqlCommand("UPDATE customers SET first_name=#first_name, last_name=#apellidos WHERE id=#id", con) ;
cm.Parameters.AddWithValue("#first_name", txtNombre.Text);
cm.Parameters.AddWithValue("#apellidos", txtApellidos.Text);
cm.Parameters.AddWithValue("#id", dgvClient.SelectedRows[0].Cells[0].Value.ToString());
It is best to always use parameters for your query, you can also look into using a framework like Entity Framework that does this automatically for you.

How can I insert data from a text field into a foreign key in the database

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 -

manually increment id in c# from mysql

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.

Csharp database application using Access Database

I'm new to programming, and trying to develop a database application with C# 2010 Express using MS Access DB 2010.
I've DataGridView and Detail view generated thru wizard on the form. I'm filtering the data with TextChanged event of a textbox.
When I navigate records, datagridview also scrolls according to current record on Detail view, and vice versa.
After filtering applied and removed this navigation behavior does not work at all (i.e. datagridview does not scroll according to current record in detail view anymore).
Any help would be appreciated.
Thanks.
Here is the code I use for filtering data (FilterField comes from Tag properties of radio buttons):
DataView dv = new DataView(personel_csDataSet.Tables["tblData"]);
dv.RowFilter = FilterField + " like '%' + '" + tbFilter.Text + "' + '%' ";
this.tblDataDataGridView.DataSource = dv;
tblDataBindingSource.Filter = FilterField + " like '%' + '" + tbFilter.Text + "' + '%' ";
That's because you set a different data source to the grid and the details view. If tblDataBindingSource is the data source of the detail view, assign it as a data source of the grid and don't create another view:
this.tblDataDataGridView.DataSource = tblDataBindingSource;
tblDataBindingSource.Filter = FilterField + " like '%' + '" + tbFilter.Text + "' + '%' ";
BTW, you don't have to assign the data source exactly there. You can do it in the beginning and you don't have to reassign it after applying a filter.

Question about adding to database from text entered into textbox

I have an app that displays data from a sql database in a datagrid. I am adding a feature that will allow a user to add a new item to this datagrid. I will have an Add button in the app that when clicked, will open a new window where all the info will be added. After the user inputs the info into the text boxes and clicks save, that info gets saved to the database. This will require inserting data into two separate tables that are related. The first table is ItemDescriptor and the other table is Accessories. The id for ItemDescriptor has to be put into the Accessories table as ItemDescriptorID. I have tried to do two separate insert queries but cant figure out how to get the id from ItemDescriptor into the Accessories table programatically. Sorry, I know this might be a little confusing. Let me know if more info is needed. Thanks
_dbAccess.ExecuteNonQuery("INSERT INTO ItemDescriptor (id, Model, Brand, DeviceName, Type, Notes) VALUES ('" + System.Guid.NewGuid() + "', '" + tbModel.Text + "', '" + tbBrand.Text + "', '" + tbDeviceName.Text + '", '" + cmbType.SelectedValue + "', '" + tbNotes.Text + "')");
_dbAccess.ExecuteNonQuery("INSERT INTO Accessories (id, ItemDescriptorID, StorageRoomCount, OnHandCount, HiBayCount) VALUES ('" + System.Guid.NewGuid() + "', '" +
and thats about as far as i got...not sure how to get the ItemDescriptorID in there from the first query.
First, please please please use parameterized queries when dealing with user-supplied input. That string concatenation stuff is just asking for a SQL injection attack.
Second of all, if you're using SQL Server, you can use something like ##IDENTITY to get the identity field after insertion. There's something comparable on all systems, so if you let us know what you're using we can point you in the right direction.
I'm assuming that you're using SQL Server and that ItemDescriptor.id is an identity column; correct?
If you execute the following command immediately after your initial insert statement, it will return the value of the most recently generated identity:
var newID = _dbAccess.ExecuteScalar("SELECT Scope_Identity()");
You can use newID to construct your second insert statement.
One caveat: The SELECT Scope_Identity() statement must be executed on the same connection instance as the initial insert statement. So ensure that you're not closing and reopening your connection between statements. If this seems to be a problem, you can actually combine your insert and select statements into a single command; e.g.:
var newID = _dbAccess.ExecuteScalar("INSERT [all your code here]; SELECT Scope_Identity();");
Good luck!
Check out this site about Getting the identity of the most recently added record
I figured out a way to make it work. I just made the guid an object and then used it as a variable and that worked. thanks for all the suggestions.
Guid guid = System.Guid.NewGuid();
if (_dbaccess != null)
{
_dbAccess.ExecuteNonQuery("INSERT INTO ItemDescriptor (id, Model, Brand, DeviceName, Type, Notes) VALUES ('" + guid + "', '" + tbModel.Text + "', '" + tbBrand.Text + "', '" + tbDeviceName.Text + '", '" + cmbType.SelectedValue + "', '" + tbNotes.Text + "')");
_dbAccess.ExecuteNonQuery("INSERT INTO Accessories (id, ItemDescriptorID, StorageRoomCount, OnHandCount, HiBayCount) VALUES ('" + System.Guid.NewGuid() + "', '" + guid + "', '" + tbStorageRoom.Text + "', '" + tbOnHand.Text + "', '" + tbHiBay.Text + "')");
}

Categories

Resources