one button click creates two events - c#

I need to create a button that makes two events and saves it into database (arrival and departure time of employee).
What i need to do First click on button saves arrival time of employee to database, Second click on same button saves departure time of employee (instead of having 2 buttons ofcourse)
I think i need some kind of counter that counts button clicks, or something like that, but i really have no clue how to program sth like that, so if you could please help me out.
This is what i have so far Please notice that the code does not work, so there is no problem except for me not knowing how to program it. Thank you
int counter = 0;
public void button1_Click(object sender, EventArgs e)
{
counter++;
try
{
if (counter == 1)
{
OleDbConnection myConnection= new OleDbConnection("\\CONNECTION PATH");
OleDbCommand cmd = new OleDbCommand();
cmd.Connection = myConnection;
cmd.CommandText = "Insert into Weekdays (Arrival)" + "values(#Arrival)";
cmd.Parameters.AddWithValue("#Arrival", DateTime.Now);
myConnection.Open();
cmd.ExecuteNonQuery();
MessageBox.Show("Arrival added.");
myConnection.Close();
}
else if (counter == 2)
{
OleDbConnection myConnection= new OleDbConnection("\\CONNECTION PATH");
OleDbCommand cmd = new OleDbCommand();
cmd.Connection = myConnection;
cmd.CommandText = "Insert into Weekdays (Departure)" + "values(#Departure)";
cmd.Parameters.AddWithValue("#Departure", DateTime.Now);
myConnection.Open();
cmd.ExecuteNonQuery();
MessageBox.Show("Departure added.");
myConnection.Close();
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}

You could create a bool to indicate whether the employee is clocked in yet or not.
bool clockedIn = false;
public void button1_Click(object sender, EventArgs e)
{
if (!clockedIn)
{
// employee just arrived - log arrival time
}
else
{
// employee leaving - log departure time
}
clockedIn = !clockedIn;
}

Quick and dirty way:
private void button1_Click(object sender, EventArgs e)
{
if (button1.Tag == null)
{
button1.Tag = "toogled";
// run event 1
}
else
{
button1.Tag = null;
// run event 2
}
}

Related

Display data's from data table on specific way

I have table in database something like this:
nickname
password
John12
123456
Nick55
666777
After that, I created a Web Site project, opened the default.aspx page, made a connection... My task is to write a function for the button, which will print the first row of the table (usernames) after 1 click, and the 2nd row (passwords) after the second click.
protected void Page_Load(object sender, EventArgs e) {}
public int temp;
protected void Button1_Click(object sender, EventArgs e)
{
SqlConnection konekcija = new SqlConnection("Data Source=DESKTOP-UF4RMH6;Initial Catalog=Server;Integrated Security=True");
try
{
konekcija.Open();
SqlCommand upit = new SqlCommand("select * from Korisnici", konekcija);
SqlDataReader dr = upit.ExecuteReader();
while (dr.Read())
{
Label1.Text += dr[temp] + " ";
}
temp++;
Label1.Text += temp + " ";
dr.Close();
}
catch (SqlException ex)
{
Response.Write(ex);
}
finally {
konekcija.Close();
}
}
When I run a site, and try this, it doesen't work, but its perfectly work when I use WindowsForms. Can anyone explain me why and how to solve it.

Delete a row from a table, specified by the user, with the click of a button in C#

I am using Visual Studio 2019 Winforms C# .NET Framework and in the Winforms project, there is a textbox and a button.
When I type a parameter name in the textbox and click the button, I want to delete the row from the table called "Serial_Key".
private void button1_Click(object sender, EventArgs e)
{
string mainconn = ConfigurationManager.ConnectionStrings["Myconnection"].ConnectionString;
SqlConnection sqlconn2 = new SqlConnection(mainconn);
string sqlquery = "select * from [dbo].[Serial-Keys] where Serial_Key=#Serial_Key";
sqlconn2.Open();
SqlCommand sqlcomm = new SqlCommand(sqlquery, sqlconn2);
sqlcomm.Parameters.AddWithValue("#Serial_Key", SerialKeyBox.Text);
SqlDataAdapter sda = new SqlDataAdapter(sqlcomm);
DataTable dt = new DataTable();
sda.Fill(dt);
sqlcomm.ExecuteNonQuery();
if (dt.Rows.Count > 0)
{
Cursor.Current = Cursors.WaitCursor;
try
{
}
catch (Exception)
{
}
Cursor.Current = Cursors.Default;
}
else
{
MessageBox.Show("Invalid Serial Key!");
label7.Text = "Serial Key Rejected...";
}
}
Change your select statement to a delete statement and remove all the DataAdaptor stuff as thats only required if you are querying records.
private void button1_Click(object sender, EventArgs e)
{
string mainconn = ConfigurationManager.ConnectionStrings["Myconnection"].ConnectionString;
SqlConnection sqlconn2 = new SqlConnection(mainconn);
// Use a Delete statement, not a select
string sqlquery = "delete from [dbo].[Serial-Keys] where Serial_Key = #Serial_Key";
sqlconn2.Open();
SqlCommand sqlcomm = new SqlCommand(sqlquery, sqlconn2);
// Construct the parameter yourself with the correct datatype and precision
sqlcomm.Parameters.Add(new SqlParameter("#Serial_Key", SqlDbType.VarChar, 32) { Value = SerialKeyBox.Text });
// Remove all the DataAdaptor stuff
// ExecuteNonQuery returns the rows affected
int numberOfRecords = sqlcomm.ExecuteNonQuery();
if (numberOfRecords > 0)
{
// Any code to run on an effective delete
}
else
{
MessageBox.Show("Invalid Serial Key!");
label7.Text = "Serial Key Rejected...";
}
}
If you install Dapper then your code becomes very simple:
private async void button1_Click(object sender, EventArgs e)
{
using(var c = new SqlConnection(_connStr))
await c.ExecuteAsync("DELETE FROM dbo.[Serial-Keys] WHERE serial_key = #sk", new { sk = SerialKeyBox.Text });
}
And, bonus, it doesn't jam your UI while it runs queries
I recommend you put that string mainconn = ConfigurationManager.ConnectionStrings["Myconnection"].ConnectionString; into a class level variable called _connStr instead, to help tidy things up
http://dapper-tutorial.net (no affiliation)

Insert multiple dynamic text box data into database

My goal is to... Click on a button and it creates some text boxes. User types in the info and if there is more info (in this case different houses they might be interested in ) to put in. They keep clicking the add button and more boxes appear. When they are done they click insert and all of the data inserts.
Right now what I have is a user can click it once and insert data and it works. What I am having trouble with is having a way to keep the ID counted in a way where I don't have to type in "txtDynamic1", "txtDyamic2", etc..
Also, the parameter #name can only be used once. So I don't understand if the only way to do this would be to click insert and then it wipes the data from the text box and they can retype for more.
I am not sure if my envision is possible where they could click however many adds for text boxes and then insert it all with one button click. I have a gridview for this set up but it does it one at a time as well... Any help would be so much appreciated as I have sunk way too many hours into this.
Sorry if this isn't explained clearly enough as my brain is fried at this point.
public partial class Sold : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
List<string> keys = Request.Form.AllKeys.Where(key => key.Contains("txtDynamic")).ToList();
int i = 1;
foreach (string key in keys)
{
this.CreateTextBox("txtDynamic" + i);
i++;
}
}
protected void Button1_Click(object sender, EventArgs e)
{
int j = 1;
for (j = 1; j < 3; j++)
{
int index = pnl.Controls.OfType<TextBox>().ToList().Count + 1;
this.CreateTextBox("txtDynamic" + index);
}
}
private void CreateTextBox(string id)
{
TextBox txt = new TextBox();
txt.ID = id;
pnl.Controls.Add(txt);
// Literal lt = new Literal();
// lt.Text = "<br />";
// pnl.Controls.Add(lt);
}
protected void Button2_Click(object sender, EventArgs e)
{
string constr = ConfigurationManager.ConnectionStrings["constr"].ConnectionString;
using (SqlConnection con = new SqlConnection(constr))
{
using (SqlCommand cmd = new SqlCommand("INSERT INTO TI_Homes(CustomerID, Year, Make, Size, Owed, Offer, Wholesale) VALUES('1000', #name, #year, '80ft', '100,000', '80,000', 'Wholesale?')"))
{
cmd.Connection = con;
cmd.Parameters.AddWithValue("#name", (pnl.FindControl("txtDynamic1") as TextBox).Text);
cmd.Parameters.AddWithValue("#year", (pnl.FindControl("txtDynamic2") as TextBox).Text);
con.Open();
cmd.ExecuteNonQuery();
con.Close();
}
}
}
}
Although I advise against trying to do this on the server side, what you need to do is keep their state on postback meaning you will have to store them in something like session or viewstate (boo) restore them on postback and then loop over the form controls in your button click. Then you will have access to the #name parameter line by line in the loop (only needing it once). Below is the idea but I haven't used web forms in years so you'll need to check the syntax.
protected void Button2_Click(object sender, EventArgs e)
{
foreach(var control in Page.Controls)
{
if(control is TextBox)
{
if(((TextBox)control).ID.IndexOf("txtDynamic") != -1)
{
string constr = ConfigurationManager.ConnectionStrings["constr"].ConnectionString;
using (SqlConnection con = new SqlConnection(constr))
{
using (SqlCommand cmd = new SqlCommand("INSERT INTO TI_Homes(CustomerID, Year, Make, Size, Owed, Offer, Wholesale) VALUES('1000', #name, #year, '80ft', '100,000', '80,000', 'Wholesale?')"))
{
cmd.Connection = con;
cmd.Parameters.AddWithValue("#name", ((TextBox)control).Text);
cmd.Parameters.AddWithValue("#year", (pnl.FindControl("txtDynamic2") as TextBox).Text);
con.Open();
cmd.ExecuteNonQuery();
con.Close();
}
}
}
}
}
}
}

access database not updating in DataGridView after deletion of a row

I am developing an Application for Computers store and i need an option to delete a product from the store , so i created a DataGridView and the data source of it was the database file of access.
when i debugged for the first time , i deleted a row and it updated in the DataGridView and Updated in the Access database file , but when i exit the app an re-debug , the list shows the deleted row one more time (Althought it's not showen in the access database file).
and it also causes error (SystemNullReferenceException) now when i delete any row
Am using OleDb provider.
here is my code:
namespace CompStore
{
public partial class ProductRemove : Form
{
private string str = #"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=J:\C#\CompStore\Store.accdb";
OleDbConnection con;
OleDbCommand com;
public ProductRemove()
{
con = new OleDbConnection(str);
InitializeComponent();
}
private void ProductRemove_Load(object sender, EventArgs e)
{
// TODO: This line of code loads data into the 'storeDataSet.Products' table. You can move, or remove it, as needed.
this.productsTableAdapter.Fill(this.storeDataSet.Products);
}
private void button1_Click_1(object sender, EventArgs e)
{
con.Open();
for (int i = 0; i < dataGridView1.Rows.Count; i++)
{
DataGridViewRow delrow = dataGridView1.Rows[i];
if (delrow.Selected == true)
{
try
{
com.CommandText = "DELETE FROM Products WHERE ProductID=" + dataGridView1.Rows[i].Cells[0].Value + "";
com.Connection = con;
int count = com.ExecuteNonQuery();
}
catch (Exception ex) { MessageBox.Show(ex.ToString()); }
dataGridView1.Rows.RemoveAt(i);
}
}
con.Close();
}
}
}
I think the issue is that you are removing items as you move through them.
what may help is to create a list of id's to remove. then at the end remove them all and rebind the grid.
something like this:
var idsToRemove = new List<int>();
var rowsToRemove = new List<int>();
for (int i = 0; i < dataGridView1.Rows.Count; i++)
{
DataGridViewRow delrow = dataGridView1.Rows[i];
if (delrow.Selected == true)
{
try
{
//com.CommandText = "DELETE FROM Products WHERE ProductID=" + dataGridView1.Rows[i].Cells[0].Value + "";
//com.Connection = con;
//int count = com.ExecuteNonQuery();
idsToRemove.add(dataGridView1.Rows[i].Cells[0].Value);
}
catch (Exception ex) { MessageBox.Show(ex.ToString()); }
//dataGridView1.Rows.RemoveAt(i);
//^this changes the list length throws things off
rowsToRemove.Add(i);
}
}
con.Open();
com.CommandText = "DELETE FROM Products WHERE ProductID in(" + string.join(',', idsToRemove.ToArray() + ")";
con.Close();
//now rebind your grid so it has the right data
// or for each row to remove dataGridView1.Rows.RemoveAt(arow)
hope this helps
I think this code might work for solving your DataGridView problem (I use this code for myself):
private void button1_Click_1(object sender, EventArgs e)
{
foreach (DataGridViewRow item in this.datagridview1.SelectedRows)
{
datagridview1.Rows.RemoveAt(item.Index);
}
}
(Writing this complete foreach code snippet will be better than just writing the statement inside it, make sure this code snippet is outside the for loop!)
You can write this code before writing the code for deleting the row(s) of the database.
Hope this helps for you too. Send me a response when you(or anyone else) try this code to tell if it worked or not.

updating the datagridview [duplicate]

This question already has an answer here:
how to update data grid view in winforms?
(1 answer)
Closed 9 years ago.
i have 2 forms and dont know how to update the datagridview, if some can simply guide me please. form1 is as follows:
public partial class frmBooking : Form
{
//instance of sqlConnection created
SqlConnection con = new SqlConnection("Data Source=....");
public frmBooking()
{
InitializeComponent();
//sets the time selecter to a time format and selects the hours and mins only in 24 hour format.
TimeOfBooking.CustomFormat = "HH:mm";
TimeOfBooking.Format = System.Windows.Forms.DateTimePickerFormat.Custom;
//combo box get data from database and updates when new customer is added
try
{
con.Open();
}
catch (SqlException ex)
{
MessageBox.Show(ex.Message, Application.ProductName, MessageBoxButtons.OK, MessageBoxIcon.Error);
Application.Exit();
}
NameOfCustomer.Items.Clear();
SqlCommand cm = new SqlCommand("SELECT GroupName FROM Customer ORDER BY GroupName ASC", con);
try
{
SqlDataReader dr = cm.ExecuteReader();
while (dr.Read())
{
NameOfCustomer.Items.Add(dr["GroupName"]);
}
dr.Close();
dr.Dispose();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, Application.ProductName, MessageBoxButtons.OK, MessageBoxIcon.Error);
}
//ends here
}
//sets the facility name so its copied from the previous(facility to be booked) form into the Facility text box
public void setFacility(string new_facility)
{
Facility.Text = new_facility;
}
//sets the date so its copied from the previous(facility to be booked) form into the date text box
public void setDate(string new_date)
{
Date.Text = new_date;
}
//adding a new customer button, redirects user to the add customer page
private void btnAddCust_Click(object sender, EventArgs e)
{
frmNewCustomer newCust = new frmNewCustomer();
newCust.Show();
this.Close();
}
//cancel button will redirect the user to the main page
private void btnCancel_Click(object sender, EventArgs e)
{
Form3 frm3 = new Form3();
frm3.Show();
this.Close();
}
private void frmBooking_Load(object sender, EventArgs e)
{
// TODO: This line of code loads data into the 'usersDataSet.Customer' table. You can move, or remove it, as needed.
this.customerTableAdapter.Fill(this.usersDataSet.Customer);
// TODO: This line of code loads data into the 'usersDataSet.Customer' table. You can move, or remove it, as needed.
this.customerTableAdapter.Fill(this.usersDataSet.Customer);
// TODO: This line of code loads data into the 'usersDataSet.Customer' table. You can move, or remove it, as needed.
this.customerTableAdapter.Fill(this.usersDataSet.Customer);
}
private void lblBookingForm_Click(object sender, EventArgs e)
{
}
private void btnConfirm_Click(object sender, EventArgs e)
{
//validation - if any of the mandotory fields are empty an error message will apear next to the text box
if (Facility.Text == "")
{
//MessageBox.Show("Please enter valid Facility, Date, Name Of Customer, Time Of Booking and Hours");
errorFacility.SetError(Facility, "Enter A Facility To Book");
}
else if (Date.Text == "")
{
errorDate.SetError(Date, "Enter A Valid Date");
}
else if (NameOfCustomer.Text == "")
{
errorCust.SetError(NameOfCustomer, "Enter A Customer To Book");
}
else if (TimeOfBooking.Text == "")
{
errorTime.SetError(TimeOfBooking, "Enter A Time To Book");
}
else if (Hours.Text == "")
{
errorHours.SetError(Hours, "Enter The Hours To Book");
}
//so if there isnt no error in the fields itll go on and add the data in to the database.
else
{
//instance of sqlConnection
SqlConnection con = new SqlConnection("Data Source=...");
//instance of sqlCommand
String query =
"INSERT INTO [Booking] values ('"
+ Facility.Text
+ "', '" + Date.Text
+ "', '" + NameOfCustomer.Text
+ "', '" + TimeOfBooking.Text
+ "', '" + Hours.Text
+ "', '" + Paid.Text
+ "', '" + Notes.Text
+ "')";
SqlCommand cmd = new SqlCommand(query, con);
con.Open();
cmd.ExecuteNonQuery();
//query executed correcty or not
con.Close();
MessageBox.Show("Sucessfully Booked");
Form3 mainPage = new Form3();
mainPage.Show();
this.Close();
}
}
}}
this is the form i am using to add a Booking.
The second form i have is the one with the datagridview, which i want to update when the booking is made the code for that is as follows:
public partial class frmViewBookings : Form
{
public frmViewBookings()
{
InitializeComponent();
}
private void btnClose_Click(object sender, EventArgs e)
{
Form3 mainpage = new Form3();
mainpage.Show();
this.Close();
}
private void frmViewBookings_Load(object sender, EventArgs e)
{
// TODO: This line of code loads data into the 'usersDataSet1.Booking' table. You can move, or remove it, as needed.
this.bookingTableAdapter.Fill(this.usersDataSet1.Booking);
}
}
}
To display data on your datagrid you would have to set it's Datasource first which you would do like this
datagridview1.Datasource = this.usersDataSet1.Booking.DefaultView
Whenever you want to refresh it you will just have to fill your tableadapter again and set your gridview's datasource to it.
(Create a seperate method to load datagridview)

Categories

Resources