Joining two ID's together to get another Column Result - c#

I am using Windows Form and C# and an SQlite Database. I have a Combo Box with the Player's Name and below i have a textbox which i need to fill with the Overall Rating
I have two tables named Player and Player_Attributes. Now i need to join the Player_Api_ID so that i can get the Overall Rating Result from the Player_Attributes table according to the Player's Name found in the Player Table. Can someone show me how the statement can be done? Thanks
Player Table1
Player_Attributes Table
UI
Dropdown Code
private void playersListBox_SelectedIndexChanged(object sender, EventArgs e)
{
try
{
string filename = #"C:\Users\nicho\Documents\nicholas2ndyearproject\database.sqlite";
var conn = new SQLiteConnection("Data Source=" + filename + ";Version=3;");
{
using (SQLiteCommand cmd = new SQLiteCommand("SELECT player_name, Player_Attributes.sprint_speed FROM Player JOIN Player_Attributes ON Player.player_api_id = Player_Attributes.player_api_id;"))
{
cmd.CommandType = CommandType.Text;
cmd.Connection = conn;
conn.Open();
cmd.Parameters.AddWithValue("#player_api_id", playersListBox.SelectedValue);
SQLiteDataReader reader = cmd.ExecuteReader();
if (reader.Read())
{
txtRating.Text = reader["rating"].ToString();
}
conn.Close();
}
}
}
catch (Exception)
{
throw;
}
}

Hope this is what you want if my assumption is correct.
SELECT FirstName, LastName, Player_Attributes.overall_rating
FROM Player JOIN Player_Attributes
ON Player.Player_api_id= Player_Attributes.Player_api_id
I hope your overall logic is wrong - playersListBox_SelectedIndexChanged() in this change event you needs to bind all the values.
for example.
txtRating.Text = queryresultobject.overall_rating.value;
txtName.Text = queryresultobject.Name;
Like above onchange event you needs to bind the values. First go through how to bind values onchange of dropdown in asp.net
This link will give you more clarity on how to implement
Edited - changed join logic

Related

Trying to UPDATE the SELECTED row from the database in c#

I'm trying to give my client a way to SELECT a specific row by typing the id which is the auto incremented primary key of the table.
But there's an issue Showing the Selected row to the client using Text Boxes and letting the client UPDATE the row's cells by editing the Text Boxes and pressing another button.
I'd be glad if you guide be how to do this since I haven't got any help from the search results.
Here's the uncompleted code:
private void LookUpBtn_Click(object sender, RoutedEventArgs e)
{
if (UserIDUpdateTB.Text == "")
{
MessageBox.Show("Customer ID is needed.", "Error");
}
else
{
SqlConnection con = new SqlConnection(#"Data Source=DESKTOP-8QAH8VK\SQLDB; Initial Catalog=Restaurant_DB; Integrated Security=True;");
con.Open();
SqlCommand lookforcustomer = new SqlCommand("LookForCustomer", con);
lookforcustomer.CommandType = CommandType.StoredProcedure;
lookforcustomer.Parameters.AddWithValue("userid", UserIDUpdateTB.Text);
//lookforcustomer.ExecuteNonQuery();
SqlDataReader reader = lookforcustomer.ExecuteReader();
reader.Read();
object test = reader.GetValue(1);
MessageBox.Show(test.ToString(), "Error");
var id = (int?)lookforcustomer.ExecuteScalar();
con.Close();
}
}
Here's the user interface:
The client enters the customer ID , presses the look up button and five cells of the row which belongs to the entered ID, appear in five other Text Boxes separately. the client makes whatever changes he/she wants by Changing the Text Boxes' text and pressing the "Update Info" button.
I'd be thankful if you help.
This is not a sql/database question, its a question regarding your UI. I'm assuming its WPF, although WinForms properties were pretty similar too.
Each button should have a separate _Click event right? So in the UpdateInfo_click, you can either send a full UPDATE statement to SQL, or detect changes between a model in memory and what is in each TextBox.Text and only update those which change (or best yet in the where clause say WHERE Name = {old value})
Also on each of your buttons you can set a Command= property, which is needed if this were part of a repeater or similar, and you can have the same handler inspect what command it was called with to determine the action needing to be taken
So I think if I understand right, basically what you want to do is pull a customers information when the lookup button is clicked, and update the customers information when the submit button is clicked. Possibly you want to also be able to add new records?
Some of the data readers are a little different, I've used Odbc and Npgsql. But I will try and show the basics of what you want below.
I like to have a separate class that deals with the Database connection, I use a method similar to this to run queries.
private SqlDataReader Query(string query)
{
SqlCommand command = null;
SqlDataReader result_reader = null;
try
{
//conn.Open();
command = new SqlCommand(query_to_perform, database_connection); //database_connection is the same as the as your "con" variable
result_reader = command.ExecuteReader();
this.successful_query = true;
this.error_message = "";
//conn.Close();
}
catch (SqlException ex)
{
this.successful_query = false;
this.error_message = ex.Message;
//destroy the connection on a failure
database_connection = new SqlConnection();
throw;
}
return result_reader;
}
Next we basically need to fill the text boxes from a select statement where the customer id is equal to the customer id on the table
private void LookUpBtn_Click(object sender, RoutedEventArgs e)
{
SqlDataReader reader = ConnectionClass.Query("SELECT * WHERE customer_id = '" + customerIdTextbox.Text + "';")
if (reader.Read())
{
//reader[0] probably is CustomerId
NameTextbox.Text = reader[1].ToString();
LastNameTextbox.Text = reader[2].ToString();
PhoneNumberTextbox.Text = reader[3].ToString();
CellphoneNumberTextbox.Text = reader[4].ToString();
AddressTextbox.Text = reader[5].ToString();
}
}
Update the customer, I'd suggest disabling the CustomerId box after they pull up an account, or they might change the number and update a different customer with all the information pulled from the first customer,
private void SubmitBtn_Click(object sender, RoutedEventArgs e)
{
if (//!exists)
{
CreateNewCustomer();
}
else
{
ConnectionClass.Query("UPDATE table SET name = '" + NameTextbox.Text + "', lastname = '" + LastNameTextbox.Text + "', phonenumber = '" + PhoneNumberTextbox.Text + "', cellphonenumber = '" + CellphoneNumberTextbox.Text + "', address = '" + AddressTextbox.Text + "' WHERE CustomerID = '" + customerIdTextbox.Text + '";");
}
}
I believe this should give you the very basics of what you are trying to do, you can still do the queries the way you were if you don't want to create a separate class to deal with the db connection. You might also want to look in to preventing SQL Injections, you will need to deal with things like apostrophes in the text, and creating a new customer will just use an insert query.

c# how to access data fields of the selected in DataGridView database record

I'm new to the database programming, so I have probably very simple question.
On the form I have a DataGridView which shows all records from the SQL database, from single table. When I select a line (OnRowEnter event), I would like to display the same data in the textBoxes, which are not binded to the DataSource, but I do not know how to access the selected record and its fields.
I have seen many examples which use SQL statements, but is it the only way? Or is there a simpler method. I thought I should be able to access the current record and its fields almost directly? Is it possible?
I'm using Visual Studio Community 2013
Thx in advance for your help.
private void dataGridView1_RowEnter(object sender, DataGridViewCellEventArgs e)
{
string asd = dataGridView1.Rows[e.RowIndex].Cells["NameOfColumn"].Value.ToString();
}
You can access any column of any row by this line.
EDIT:
You just told me you want to populate 2 textboxes from database and on buttons(save - overwrite) you want to save/overwrite it. So why you do not populate it from database
using (FbConnection con = new FbConnection(connectionString))
{
con.Open();
using (FbCommand cmd = new FbCommand("SELECT TEXT1, TEXT2 FROM TABLE WHERE CONDITION", con))
{
FbDataReader dr = cmd.ExecuteReader();
if(dr.Read())
{
textBox1.Text = dr[0].ToString();
textBox2.Text = dr[1].ToString();
}
}
con.close();
}
and then after user press save you just take whole text and update database
using (FbConnection con = new FbConnection(connectionString))
{
con.Open();
using (FbCommand cmd = new FbCoimmand("UPDATE TABLE SET TEXT1 = #Text1, TEXT2 = #Text2 WHERE CONDITION))
{
cmd.Parameters.AddWithValue("#Text1", textBox1.Text);
cmd.Parameters.AddWithValue("#Text2", textBox2.Text);
cmd.ExecuteNonQuery();
}
con.Close();
}
if user is writing text in some other textbox and you want to add that text to current text in database so you just read text from database and put it in string, on that string you add string from user and save like that to database

C# WinForm List into Database

Afternoon All,
I have been tasked with turning what is currently a paper-based form which our users fill in, into an electronic form in a Windows Form c# application, where the user can fill it in electronically then click a button, which puts the data in the database.
I have already completed 5 other forms with no issues, however the one I have just reached, which I thought would be the simplest, has stumped me.
This is an example of what the paper one looks like and how it is filled in (it gets printed from excel first):
My database has the following tables:
User
UserID
UserName
EquipmentReturnSubmission
UserID (from User table)
ReturnID
ReturnDate
EquipmentReturnDetails
ReturnID (from EquipmentReturnSubmission table)
SerialNo
Description
When the data is put into the database, each row on the form above will have a row in the EquipmentReturnDetails table, but all have the same ReturnID, so this can be linked to produce a list of the equipment submitted by that user.
The bit that has stumped me is how to do this in my WinForms application. I've had a look at inserting data from a GridView into a database, but can only find how to do this one row at a time - i need this to insert all of the rows using the same ReturnID so it can be linked.
I thought I could do something like below, but not a clue where to start to get it coded, nor even if this is the best way to do it.
My thinking is that the user enters the serial number and description, and clicks add, which puts the details into listbox/gridview or some kind of holding area, and clears the text boxes. The user can then keep doing this, each time the details are added to the holding area, then the submit button writes it to the database.
Again i'm not sure how this could be done unless there's a way to create a parameter each time the Add button is clicked.
If anyone could point me in the right direction that would be great. I'm self taught so happy to be completely corrected.
Thanks in advance.
Well, thanks to Zath's comment I did a bit more research and managed to get this working with the below:
Tables:
User
UserID
UserName
EquipmentReturnSubmission
UserID //(from User table)
ReturnID
ReturnDate
EquipmentReturnDetails
ReturnID //(from EquipmentReturnSubmission table)
SerialNo
Description
I then added a DataGridView to my form, and added the columns SerialNo and Description. My C# code below:
private void Submit_Click(object sender, EventArgs e)
{
if (MessageBox.Show("Are you sure these details are correct?", "Are you sure?", MessageBoxButtons.YesNo) == DialogResult.Yes)
{
dataGridView1.AllowUserToAddRows = false; //Disables edit so the insert doesnt try and do an insert for the blank row created when the user clicks to add data.
#region SQL Insert
SqlConnection con = new SqlConnection(Home.ConString);
SqlCommand cmd = new SqlCommand("EquipmentReturnSubmission1", con);
cmd.CommandType = CommandType.StoredProcedure;
#region Parameters
cmd.Parameters.Add("#Name", SqlDbType.VarChar, 200).Value = OfficerName.Text;
cmd.Parameters.Add("#Area", SqlDbType.VarChar, 200).Value = Area.Text;
cmd.Parameters.Add("#SubmissionDate", SqlDbType.Date).Value = SubmissionDate.Value;
cmd.Parameters.Add("#SubmissionID", SqlDbType.Int).Direction = ParameterDirection.Output;
#endregion
try
{
con.Open();
cmd.ExecuteNonQuery();
}
catch (System.Exception ex1)
{
throw new System.Exception("Error submitting equipment return sheet." + ex1.Message);
}
finally
{
SubID = int.Parse(Convert.ToString(cmd.Parameters["#SubmissionID"].Value));
con.Close();
SecondInsert();
}
#endregion
}
}
}
private void SecondInsert()
{
foreach (DataGridViewRow row in dataGridView1.Rows)
{
SqlConnection con = new SqlConnection(Home.ConString);
{
SqlCommand cmd = new SqlCommand("INSERT INTO EquipmentReturnSubmissionDetails (SubmissionID, SerialNumber, Description) VALUES (#SubmissionID, #SerialNumber, #Description)", con);
cmd.CommandType = CommandType.Text;
{
cmd.Parameters.AddWithValue("#SubmissionID", SqlDbType.Int).Value = SubID;
cmd.Parameters.AddWithValue("#SerialNumber", row.Cells["SerialNo"].Value);
cmd.Parameters.AddWithValue("#Description", row.Cells["Description"].Value);
con.Open();
cmd.ExecuteNonQuery();
con.Close();
}
}
}
MessageBox.Show("Data submitted.");
this.Close();
}
This worked exactly as I required it to and does it very quickly.

button and itemcommand event sequence

Background information:
I have a SQL connected datalist, one of the columns is called work_order
In the datalist I have inserted a button btn_Start. The button is populated at the end of each set
The goal of the btn_Start is to do a database insert, the insert needs to includes the work_order value from the set of data the button is clicked in (so the insert can be tied to the work_order value.)
btn_Start code:
protected void btn_Start(object sender, EventArgs e)
{
using (SqlConnection connection = new SqlConnection(ConfigurationManager.ConnectionStrings["nothanks"].ConnectionString))
{
String query = "INSERT INTO [TimeTest] ([Starttime], [Work_Order]) VALUES (#Starttime, #Work_Order)";
using (SqlCommand CCC = new SqlCommand(query, connection))
{
connection.Open();
CCC.CommandType = CommandType.Text;
CCC.Parameters.Add("#Starttime", SqlDbType.DateTime).Value = DateTime.Now;
CCC.Parameters.Add("#Work_Order", SqlDbType.Int).Value = lb_User1.Text.ToString();
CCC.ExecuteNonQuery();
}
}
}
To grab text of the work_order column, I'm using the itemcommand event to propagate a label (lb_User1).
DataList1_ItemCommand` code:
protected void DataList1_ItemCommand(object source, DataListCommandEventArgs e)
{
DataList2.SelectedIndex = e.Item.ItemIndex;
lb_User1.Text = (DataList2.SelectedItem.FindControl("Work_OrderLabel4") as Label).Text;
}
This works well, each time btn_Start is pushed, lb_User1 is updated with the right information.
The issue: when btn_Start is clicked, both btn_Start and DataList1_ItemCommand fire. But DataList1_ItemCommand fires after btn_Start. Which means lb_User1 isn't updated with the right info yet, and as such the insert fails to work as needed.
NOTES:
the lb_User1 isn't needed, I planned to go direct to the SQL insert. lb_User1 was used for code testing (so I can see what's going on)
My objective is to do the SQL insert with the grabbed data from datalist (Work_OrderLabel4). If I can accomplish this objective a better way that would also solve the issue.
btn_Start isn't going to be the only button in the datalist. One possible solution is go way from having two events and only doing things under the itemcommand event, but how do you separate out which button fires, without involving their respective events.
Objective: I'm trying to get each embedded start button to grab its corresponding work_order value for use in a SQL insert. The above is trying to accomplish this task, I'm almost there but I'm having the issue stated above. I'm open for other ways to accomplish this task (see picture of clarification)
Additional Information:
protected void DL_Main_ItemCommand(object source, DataListCommandEventArgs e)
{
using (SqlConnection connection = new SqlConnection(ConfigurationManager.ConnectionStrings["test"].ConnectionString))
{
String query = "INSERT INTO [TimeTest] ([Starttime], [Work_Order]) VALUES (#Starttime, #Work_Order)";
using (SqlCommand CCC = new SqlCommand(query, connection))
{
connection.Open();
CCC.CommandType = CommandType.Text;
CCC.Parameters.Add("#Starttime", SqlDbType.DateTime).Value = DateTime.Now;
// All you need is the value of Work_OrderLabel4 of the selected item so just do it like this.
CCC.Parameters.Add("#Work_Order", SqlDbType.Int).Value = (DL_Main.SelectedItem.FindControl("Work_OrderLabel") as Label).Text;
CCC.ExecuteNonQuery();
}
}
}
After Running
Get rid of btnStart and put the code below in your DataList1_ItemCommand. The only line I changed is the one with my comment:
using (SqlConnection connection = new SqlConnection(ConfigurationManager.ConnectionStrings["nothanks"].ConnectionString))
{
String query = "INSERT INTO [TimeTest] ([Starttime], [Work_Order]) VALUES (#Starttime, #Work_Order)";
using (SqlCommand CCC = new SqlCommand(query, connection))
{
connection.Open();
CCC.CommandType = CommandType.Text;
CCC.Parameters.Add("#Starttime", SqlDbType.DateTime).Value = DateTime.Now;
// All you need is the value of Work_OrderLabel4 of the selected item so just do it like this.
CCC.Parameters.Add("#Work_Order", SqlDbType.Int).Value = (DataList2.SelectedItem.FindControl("Work_OrderLabel4") as Label).Text;
}
CCC.ExecuteNonQuery();
}
}
Also, as a side note, please give your controls better names than DataList1. Perhaps DataListTimeTest since it deals with TimeTest table.

saving form in database

I was wondering how could I retrieve the data from SQL server compact database that I just saved and insert it into textbox of newly created form. The source code is not complete, I just wanted to save space. Connection is fine, and I'm able to add data into database in the actual program. I just would like to know how to retrieve it and put it into textbox of newly created form. This is done in WinForms.Thank you!
public void b1_Click(object sender, EventArgs e)
{
SqlCeCommand command = new SqlCeCommand("INSERT INTO tbl1(Name) VALUES (#Name, #LastName)", conn);
command.Parameters.AddWithValue("#Name", t1.Text);
command.ExecuteNonQuery();
}
private void b2_Click(object sender, EventArgs e)
{
Form form2 = new Form();
form2.Show();
t3.Location = new System.Drawing.Point(0, 35);
t3.Size = new System.Drawing.Size(85, 15);
//access database and insert data into textbox
t3.Text = ?
form2.Controls.Add(t3);
}
Well it's not to hard to just get a value from the database, something like this should suit your needs:
SqlCeCommand command = new SqlCeCommand("SELECT * FROM tbl1(Name) WHERE name = #Name AND last_name = #LastName", conn);
command.Parameters.AddWithValue("#Name", "Hank");
command.Parameters.AddWithValue("#Name", "Hill");
SqlDataReader reader = command.ExecuteReader();
t1.Text = reader.GetString(0);
t2.Text = reader.GetString(1);
When in doubt, start at the official docs. See this sample, on msdn: http://msdn.microsoft.com/en-us/library/aa226134(v=sql.80).aspx
They show there a couple of SQL commands like SELECT, INSERT and UPDATE. You know how to insert, so you are now interested in the SELECT part. See how they use data reader and try that for starters.
Here is an example:
http://msdn.microsoft.com/en-us/library/aa983340(v=VS.80).aspx
Please also check codeplex.com for additional examples/projects

Categories

Resources