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.
Related
So I'm making a seat reservation system for a school project and I'm stuck. I'll explain exactly what I'm trying to do. I created this form:
Seat Reservation Layout
As you can see, I created a seat layout. All the seats are buttons. I also created a local SQL database with SeatID (which matches the names of the buttons exactly) and Availability (either True or False).
What I wanted to do is let the user choose seat(s) (which becomes green after clicking on it) and whenever the user clicks on the "OK" button, the seats get reserved, meaning that I want the Availability in my database corresponding with the buttonname and thus, the SeatID, to become False (meaning the seat got reserved). After running the program again, the reserved seats need to be red, on the start, meaning they can not get reserved.
So basically I managed to do it all; My database works, reserved seats are red whenever I run the program etc.
The only thing I can not get working is updating the database with reserved seats.
private void OK_Click(object sender, EventArgs e)
{
con.Open();
SqlCommand command;
SqlDataAdapter adapter = new SqlDataAdapter();
String sql = "";
command = new SqlCommand(sql, con);
foreach (Button button in buttons)
{
if (button.BackColor == Color.Green)
{
sql = "UPDATE Seats SET Availability='" + "False" + "'WHERE SeatID=" + button.Name;
adapter.UpdateCommand = new SqlCommand(sql, con);
adapter.UpdateCommand.ExecuteNonQuery();
}
}
command.Dispose();
con.Close();
}
Above you see my code where I try to update the databse. I made the list of all buttons called "buttons" and the code above looks through all the buttons and checks whether they're green or not (green == clicked, so ready to be reserved). That is supposed to happen when I click on the "OK" button. When I run this, I get this error message:
Error Message
So, what am I doing wrong? How am I supposed to update the database by checking whether the SeatID corresponds with the button name?
Thanks in advance.
EDIT: Here I attach my database:
Datatable
Data
You should use parameters in your SQL query insead.
sql = "UPDATE Seats SET Availability= #Availabe WHERE SeatID = #SeatID" ;
adapter.UpdateCommand.Parameters.AddWithValue("#Available", false); //I assume that your Availibility column is a BIT type.
//If a varchar column for exemple, you can use
//adapter.UpdateCommand.Parameters.AddWithValue("#Available", "False"); //But, you should use a bit column instead.
adapter.UpdateCommand.Parameters.AddWithValue("#SeatID", button.Name);
adapter.UpdateCommand = new SqlCommand(sql, con);
adapter.UpdateCommand.ExecuteNonQuery();
To add parameters to your SQL Command, you can take a look at this :
https://learn.microsoft.com/en-us/dotnet/api/system.data.sqlclient.sqlcommand.parameters?view=netframework-4.8
Did you try this command;
sql = "UPDATE Seats SET Availability='False' WHERE SeatID=" + button.Name;
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
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
I'm stuck with something and I'd appreciate it if anyone can assist me.
I have a simple MS Access database that's linked to my program. The first thing I did was fill a combobox with one of the fields in my database ("Product Description").
What I'd like to do is when a user selects an item in the combobox, all the other fields in the record be displayed in text boxes.
string sConnection;
sConnection = "Provider=Microsoft.ACE.OLEDB.12.0;" +
"Data Source=XYZDatabase.accdb";
OleDbConnection dbConn;
dbConn = new OleDbConnection(sConnection);
dbConn.Open();
cbxProducts.DisplayMember = "Product Description";
dbConn.Close();
I've considered using possibly SQL or a DataReader, though I'm really not sure.
This is the event where I want the textboxes to be filled. I'm literally stuck here.
private void cbxProducts_SelectedIndexChanged(object sender, EventArgs e)
{
txtProductNumber.Text =
txtProductDescription.Text =
txtProductCategory.Text =
txtProductCost.Text =
}
I hope I haven't formatted my question wrong or anything, apologies if I have, this is my first time posting here! Dx
I wonder if your combo box is actually showing data from the DB.
In the first code block after
dbConn.Open()
and before
dbConn.Close()
you should have code like this:
SqlCommand sc = new SqlCommand("select prodid, proddesc from products", conn);
SqlDataReader reader;
reader = sc.ExecuteReader();
DataTable dt = new DataTable();
dt.Columns.Add("prodid", typeof(string));
dt.Columns.Add("proddesc", typeof(string));
dt.Load(reader);
cbxProducts.ValueMember = "prodid";
cbxProducts.DisplayMember = "proddesc";
cbxProducts.DataSource = dt;
And then in the second code block you need to fetch the selected Product ID first.
private void cbxProducts_SelectedIndexChanged(object sender, EventArgs e)
{
string ID = comboBox1.SelectedValue.ToString();
//Based on ID make a sql query and fetch the details of that product from the DB.
//Follow the earlier code block to make DB connection and execute query.
//Then populate the data in individual text boxes by looping through the dr.
//I am leaving this deliberately for you to figure out and I am sure you can.
txtProductNumber.Text =
txtProductDescription.Text =
txtProductCategory.Text =
txtProductCost.Text =
}
I am using ASP.NET 4.5 C#
I have a FormView in Insert mode, linked to an MSSQL database, with 2 hidden fields in it.
These fields are populated when the page loads.
I now need this data to be inputted to the database automatically without anyone having to click on an insert button.
How do I achieve this once the data has bound?
Here is the code I have been trying, it's working except the adnumber value is not uploading, only the date
protected void FormView1_DataBound(object sender, EventArgs e)
{
string ad, insertqry;
ad = ((HiddenField)(FormView1.FindControl("Adnumber"))).Value;
DateTime hit = DateTime.Now;
insertqry = "insert AdvertsHits(ad,hit) values(#ad,#hit)";
if (con.State == ConnectionState.Closed)
{
con.Open();
}
SqlCommand cmd = new SqlCommand(insertqry, con);
cmd.Parameters.Add("#ad", SqlDbType.VarChar, 250).Value = ad;
cmd.Parameters.Add("#hit", SqlDbType.DateTime).Value = hit;
cmd.ExecuteNonQuery();
cmd.Dispose();
con.Close();
}
Write a method to insert data into data base and call that method after hidden fields get the data, then data automatically inserted into database.