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.
Related
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();
}
}
}
}
}
}
}
I am having trouble with datatableadapter.update(dataset). Everything is working until i add a new column to database, It will display the new item but when i try to update the value though the dataviewgrid. I get no errors but the data is not saved. Here is the code.
private void button2_Click(object sender, EventArgs e)
{
MessageBox.Show("Record Updated");
this.inventoryTableAdapter.Update(jobDetailsDataSet.Inventory);
}
private void button1_Click(object sender, EventArgs e)
{
this.inventoryTableAdapter.Fill(this.jobDetailsDataSet.Inventory);
}
private void btnadd_Click(object sender, EventArgs e)
{
SqlConnection cn = new SqlConnection(global::FarWest_Program.Properties.Settings.Default.JobDetailsConnectionString);
try
{
string sql;
sql = "ALTER TABLE Inventory ADD " + txtitem.Text + " VARCHAR (50)";
this.inventoryTableAdapter.Fill(this.jobDetailsDataSet.Inventory);
SqlCommand execommand = new SqlCommand(sql, cn);
cn.Open();
execommand.ExecuteNonQuery();
MessageBox.Show("You have Updated The Job Details", "Message", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
catch (Exception ex)
{
MessageBox.Show(ex.Message + Environment.NewLine + "Please Check to See you only used Numbers", "Only Numbers Allowed", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
finally
{
cn.Close();
}
}
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
}
}
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)
I have a datagrid to display some information from a SQL table, and then a simple textbox and button to allow users to add records to the database. Problem is, when the user clicks Add, the datagrid SHOULD update, but it doesn't, any ideas? The code in question is as follows:
protected void Page_Load(object sender, EventArgs e)
{
username.Text = Session["username"].ToString();
datetime.Text = DateTime.Now.ToString();
BindData();
}
protected void BindData()
{
string SQLQuery = "SELECT * From Filters";
OleDbConnection MyConn = new OleDbConnection(ConfigurationManager.ConnectionStrings["ConnStr"].ConnectionString);
DataSet resultsDataSet = new DataSet();
MyConn.Open();
OleDbDataAdapter DataAdapter = new OleDbDataAdapter(SQLQuery, MyConn);
DataAdapter.Fill(resultsDataSet);
DGFilters.DataSource = resultsDataSet;
DGFilters.DataBind();
if (resultsDataSet.Tables[0].Rows.Count == 0)
{
no_records.Visible = true;
DGFilters.Visible = false;
}
else
{
DGFilters.Visible = true;
no_records.Visible = false;
}
MyConn.Close();
}
protected void AddFilter_Click(object sender, EventArgs e)
{
OleDbConnection MyConn = new OleDbConnection(ConfigurationManager.ConnectionStrings["ConnStr"].ConnectionString);
MyConn.Open();
string SQLInsert = "INSERT INTO Filters (FilterString) VALUES ( '" + FilterToAdd.Text + "')";
OleDbCommand MyCmd = new OleDbCommand(SQLInsert, MyConn);
MyCmd.ExecuteNonQuery();
MyConn.Close();
DataBind();
}
Any ideas?
At the bottom of your AddFilter_Click method you need to call your own BindData() so the grid can be refreshed with the new record. Right now you're calling DataBind(), which is a method on the base class Control, which is being applied to your entire web form. I'm guessing this isn't doing much of anything.
Also, in your Page_Load method, you can probably change this:
BindData();
to
if (!Page.IsPostBack)
BindData();
so that you don't bind your grid twice when the user clicks on the 'add' button.