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)
Related
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.
I am trying to Enable BtnSubmit based on the length of TxtPswrd being greater than 8. I am using the Textfield Validating function, I am confused, should I used Validating, Validated or TextChanged functions?
private void BtnSignin_Click(object sender, EventArgs e)
{
// SqlConnection con = StartCon();
foreach (Control c in this.Controls)
{
if (c is TextBox)
{
TextBox textBox = c as TextBox;
if (textBox.Text != string.Empty)
{
DataInserted(sender, e);
}
else
{
MessageBox.Show("Fill All Fields", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
TxtID.Focus();
break;
}
}
}
the DataInserted function:
private void DataInserted(object sener, EventArgs e)
{
try
{
SqlConnection sqlConnection = StartCon();
string AdminLookup = "Select count(*) from signin WHERE memid = '" + TxtID.Text + "' and adminpass='"+TxtPswrd.Text+"'";
SqlCommand command = new SqlCommand(AdminLookup, sqlConnection);
command.Parameters.Clear();
command.Parameters.AddWithValue("#usr", TxtUsername.Text);
command.Parameters.AddWithValue("#pwd", TxtPswrd.Text);
if (command.ExecuteScalar().ToString() =="1")
{
SetValueForText1 = TxtUsername.Text;
new Thread(() => new PSP_Manager().ShowDialog()).Start();
this.Close();
}
else
{
MessageBox.Show("Error Signing in", "Check Credentials", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
catch (SqlException sqlexception)
{
MessageBox.Show("Error", sqlexception.Message);
}
finally
{
StartCon().Close();
}
}
I am trying to enable the BtnSubmit only when the TxtPswrd.length >= 8
help, please.
pic
I'd use a TextChanged:
private void PasswordTextbox_TextChanged(object sender, EventArgs e){
submitButton.Enabled = passwordTextbox.Text.Length >= 8;
}
because I'd want the submit button to enable while they were still focused in the box, as soon as they'd typed 8 chars
In other news, don't write SQL commands like that; see http://Bobby-tables.com for why..
..and also don't store passwords in plaintext in a database; doing so is the reason http://haveibeenpwned.com has to exist
I have an application like this:
There's one main form (frmMasuk) with datagrid and "Add New" button
When someone clicks Add New, it shows the dialog form (Form2) to add new data.
When someone clicks "Save" on dialog form, it will be closed and
the datagrid will be refreshed
I got a problem when the dialog form closes, the datagrid must be refreshed.
This is some of my code:
frmMasuk:
public frmMasuk()
{
InitializeComponent();
SqlCommand sql = new SqlCommand("SELECT * FROM kas ORDER BY id_kas, tanggal DESC", koneksi.mykonek);
koneksi.openkonek();
SqlDataReader reader = sql.ExecuteReader();
DataTable a = new DataTable();
a.Load(reader);
koneksi.closekonek();
dgv.DataSource = a;
dgv.Enabled = true;
}
private void button3_Click(object sender, EventArgs e)
{
frmKasNew a = new frmKasNew();
a.ShowDialog();
}
frmKasNew:
private void simpankas()
{
koneksi.openkonek();
DateTime tgl = Convert.ToDateTime(ttanggal.Text);
SqlCommand sql = new SqlCommand("INSERT INTO kas(tanggal, jenis, jumlah, keterangan) VALUES('"+ tgl +"','"+ tjenis.Text +"','" + tjumlah.Text + "','" + tket.Text +"') ",koneksi.mykonek);
int exe = sql.ExecuteNonQuery();
if (exe == 0)
{
MessageBox.Show("Data gagal disimpan ke database", "Aplikasi KAS Usaha", MessageBoxButtons.OK, MessageBoxIcon.Warning);
}
else
{
MessageBox.Show("Data berhasil disimpan!", "Aplikasi KAS Usaha", MessageBoxButtons.OK, MessageBoxIcon.Information);
this.Dispose();
}
}
private void button3_Click(object sender, EventArgs e)
{
if (ttanggal.Text == "" || tjenis.Text == "" || tjumlah.Text == "" || tket.Text == "")
{
MessageBox.Show("Harap melengkapi data sebelum menyimpan","Aplikasi KAS Usaha",MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
}
else
{
simpankas();
}
// end if
}
Add an event to the a.OnClose event:
private void button3_Click(object sender, EventArgs e)
{
frmKasNew a = new frmKasNew();
a.FormClosed += FormClosed;
a.ShowDialog();
}
private void FormClosed(object sender, FormClosedEventArgs e)
{
SqlCommand sql = new SqlCommand("SELECT * FROM kas ORDER BY id_kas, tanggal DESC", koneksi.mykonek);
koneksi.openkonek();
SqlDataReader reader = sql.ExecuteReader();
DataTable a = new DataTable();
a.Load(reader);
koneksi.closekonek();
dgv.DataSource = a;
dgv.Enabled = true;
}
Have you tried showing the form with a DialogResult like
private void button3_Click(object sender, EventArgs e)
{
frmKasNew kas = new frmKasNew();
DialogResult result = kas.ShowDialog():
If (result == DialogReult.OK)
{
CurrencyManager cm = (CurrencyManager)
dgv.BindingContext[a];
cm.Refresh();
}
Then use CurrencyManager to to refresh the datagrid?
I have got three forms, of a winform app. in which form3 there are two butons and some textboxes. I wanted to know why my form is showing a messagepop called "Duplicate" when I press the cancel button of the form.
I actually told the form3 to cancel and return to the form1. Its doing the job. but before coming to the form1 it's showing me a messagebox "Duplicate" which I don't want to see.
How can I avoid this popup?
Codes in form3
private void submit_Click(object sender, EventArgs e)
{
// this button click event handler will raise the
// event which can then intercepted by any listeners
//some codes....
this.Dispose();
}
private void cancel_Click(object sender, EventArgs e)
{
this.Close();
}
Codes in form1
private void btn_open_form3_Click(object sender, EventArgs e)
{
Form3 f = new Form3();
string l = "true";
// Add an event handler to update this form
// when the address form is updated (when AddressUpdated fires).
f.AddressUpdated += new Form3.AddressUpdateHandler(AddressForm_ButtonClicked);
f.ShowDialog();
if (String.IsNullOrEmpty(file_NameTextBox.Text.ToString()))
{
frmShowMessage.Show("Try again!!!", "Missing!!!!", enumMessageIcon.Error, enumMessageButton.OK);
//cell_check();
}
else
{
if (checkexistornot())
{
if (file_NameTextBox.Text == string.Empty)
{
cell_check();
}
else
{
SqlConnection con = new SqlConnection(#"Data Source=DVSQL\SQLEXPRESS;Initial Catalog=CncDB;Persist Security Info=True;User ID=CncDbUser;Password=*****");
con.Open();
SqlCommand cmd = new SqlCommand(#"INSERT INTO cncinfo (part,drawings,draftpath,comments) VALUES ('" + file_NameTextBox.Text + "','" + drawingsTextBox.Text + "','" + gcodeTextBox.Text + "','" + commentsTextBox.Text + "') ", con);
cmd.ExecuteNonQuery();
con.Close();
load_table();
}
}
}
}
private void AddressForm_ButtonClicked(object sender, AddressUpdateEventArgs e)
{
// update the forms values from the event args
file_NameTextBox.Text = e.File_Name;
drawingsTextBox.Text = e.Drawings;
gcodeTextBox.Text = e.Gcode;
commentsTextBox.Text = e.Comments;
}
public bool checkexistornot()
{
SqlConnection con = new SqlConnection(#"Data Source=DVSQL\SQLEXPRESS;Initial Catalog=CncDB;User ID=CncDbUser;password=*****");
con.Open();
SqlCommand cmd = new SqlCommand("select part from cncinfo where part='" + this.file_NameTextBox.Text + "' ;", con);
cmd.CommandType = CommandType.Text;
cmd.Parameters.Add("#part", SqlDbType.NVarChar).Value = Convert.ToString(dataGridView1.Rows[0].Cells["Part Number"].Value);
object obj = cmd.ExecuteScalar();
cmd.ExecuteNonQuery();
con.Close();
if (obj!=null)
{
frmShowMessage.Show(""Duplicate!!!!", enumMessageIcon.Warning, enumMessageButton.OK);//- - - ->>showing this line if i press the cancel_Click from FORM3
cell_check();
return false;
}
else
return true;
}
If you want your code to not execute code after clicking the cancel button in Form3, one option is taking advantage of the DialogResult property.
Cancel button click handler:
private void cancel_Click(object sender, EventArgs e)
{
this.DialogResult = DialogResult.Cancel;
this.Close();
}
Imediately after showing Form3 ("f.ShowDialog();")
if (f.DialogResult == DialogResult.Cancel)
{
return;
}
Hope it helps.
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
}
}