Showing message box in form2 when i press the cancel button - c#

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.

Related

Hide and Show Code doesnt work on other forms

In form 1
public void button1_Click(object sender, EventArgs e)
{
SqlConnection con = new SqlConnection(#"Data Source=.\ALLENSQL;Initial Catalog=TITOMSLogin;Integrated Security=True");
SqlDataAdapter sdf = new SqlDataAdapter("select usertype, fullname, position from login where username= '" + txtuser.Text + "' and password='" + txtpass.Text + "'", con);
DataTable dt = new DataTable();
sdf.Fill(dt);
string fullname = dt.Rows[0]["FullName"].ToString();
string position = dt.Rows[0]["Position"].ToString();
if (dt.Rows.Count == 1)
{
this.Hide();
if (dt.Rows[0]["Usertype"].ToString() == "Admin")
{
Form2Admin ss = new Form2Admin(position + ": " + fullname);
Form3Admin sa = new Form3Admin(position + ": " + fullname);
Form5 sw = new Form5(position + ": " + fullname);
ss.Show();
sa.Hide();
sw.Hide();
}
now this code doesn't work in other forms
private void button2_Click(object sender, EventArgs e)
{
this.Hide();
Form3Admin.Show();
}
this is the scenarios I am trying to achieve:
After pressing login form2 will show up, form 3 and form 4 is hidden.
button in form 2 is press (Form 2 will hide, Form 3 will show).
button in form 3 is press (Form 3 will hide, Form 4 will show).
button in form 4 is press (form 4 will hide, Form 2 will show but all data written before must still be there) and so on to the other forms.
You have to use the same actual Form3Admin instance to Show it. Keep Form3Admin sa instance as a class variable and use that instance when you want to show it.
private void button2_Click(object sender, EventArgs e)
{
this.Hide();
sa.Show();
}

C# I can't print variable text in other Form

I trying to code program and I have two forms (Form1 is for loging and Form2 is empty for now, but I would like to print Logged: 'Name' + 'Surename' from DB).
I created class User which has Name and Surename (both public static strings) and method GetUserInfo() to get Name and Surename by user's Login. If I print User.Name + User.Surename in MsgBox after program checks login and password everything is ok, but after Form2 loads then
label1.Text = "User: " + User.name + " " + User.surename;
in method public Form2() shows just User: and nothing more.
Form1:
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void textBox1_TextChanged(object sender, EventArgs e)
{
}
private void textBox2_TextChanged(object sender, EventArgs e)
{
}
private void button1_Click(object sender, EventArgs e)
{
string login = textBox1.Text;
string pass = textBox2.Text;
SqlConnection connection = new SqlConnection(#"Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=C:\Users\xxx\Documents\Visual Studio 2015\Projects\*\*\Database1.mdf;Integrated Security=True;Connect Timeout=30");
SqlCommand query = new SqlCommand("Select * from Users where login='" + login + "' AND password ='" + pass + "'", connection);
connection.Open();
SqlDataReader Reader = query.ExecuteReader();
int count = 0;
Form1 form1 = new Form1();
Form2 form2 = new Form2();
while (Reader.Read())
{
count += 1;
}
if (count == 1)
{
this.Hide();
form2.Show();
User.GetUserInfo(login);
MessageBox.Show(User.name + " " + User.surename);
}
else
MessageBox.Show("Bad Login");
}
}
Form2
public partial class Form2 : Form
{
public Form2()
{
InitializeComponent();
label1.Text = "User: " + User.name + " " + User.surename;
}
private void label1_Click(object sender, EventArgs e)
{
}
private void label1_Click_1(object sender, EventArgs e)
{
}
}
and User class:
public class User
{
public static string name { get; set; }
public static string surename { get; set; }
public static void GetUserInfo(string login)
{
using (SqlConnection connection = new SqlConnection(#"Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=C:\Users\xxx\Documents\Visual Studio 2015\Projects\*\*\Database1.mdf;Integrated Security=True;Connect Timeout=30"))
using (SqlCommand query = new SqlCommand("Select FirstName, LastName from Users where login='" + login + "'", connection))
{
connection.Open();
SqlDataReader Reader = query.ExecuteReader();
while (Reader.Read())
{
User.name = Reader["FirstName"].ToString();
User.surename = Reader["LastName"].ToString();
}
}
}
}
Thank you!
Use this code:
User.GetUserInfo(login);
this.Hide();
Form2 form2 = new Form2();
form2.Show();
because you need first set values for name and surename and then use it.
In your case, you first show Form2 and then set values
Add public variables or properties to Form1 so that you can access them:
in Form1:
public User user;
....
user.name = Textbox1.Text;
user.surname = Textbox2.Text;
In your Form2:
Form frm = new Form1();
frm.ShowDialog();
label1.Text = "User: " + frm.user.name + " " + frm.user.surename;
frm.Dispose();
So the problem you have is that you are creating Form2 before the properties in the User class are filled.
This is why :
label1.Text = "User: " + User.name + " " + User.surename;
This is called inside the constructor of Form2. This means whenever you initialize this form with
Form2 form2 = new Form2();
all code in the constructor executes.
So the label text will be set when creating the form.
User.GetUserInfo(login); is called after this, the data will be empty for Form2 since the form is already created.
A possible solution would be
To set the label in the form2 loading event and call User.GetUserInfo(login); before form2.Show();
or
Calling Form2 form2 = new Form2(); after User.GetUserInfo(login);
You are setting the label text in the constructor of Form2. At that point they don't have a value as you haven't read the data from the database yet, so the label will simply read:
User:
It won't change until you update it's value again. You need to call a method on Form2 to update the label text once the call to User.GetUserInfo has completed successfully.
if (count == 1)
{
this.Hide();
form2.Show();
User.GetUserInfo(login);
// Update the label text here
MessageBox.Show(User.name + " " + User.surename);
or swap the order of getting the user information and constructing Form2:
if (count == 1)
{
this.Hide();
User.GetUserInfo(login);
form2 = new Form2();
form2.Show();
Either way will work, the one you choose depends on what else you need to do with your forms.

Refresh Datagrid When Dialog Form Closed

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?

Connection to the database will execute only if the username is same with the database had

I got a problem here with Log on the User. Whenever I run the program, the program will not execute the Wait form, unless the Username is same with the database had.
I want to whenever the user enter the different Username with the database, the Wait form will execute too, not only when the Username is same with the database had.
Here is the code:
private void CheckUserDatabase(object sender, EventArgs e)
{
using (OleDbConnection conn = new OleDbConnection(connectionString))
{
string query = "SELECT * FROM [Member] WHERE [Username] = #Username";
conn.Open();
using (OleDbCommand cmd = new OleDbCommand(query, conn))
{
cmd.Parameters.Add("#Username", System.Data.OleDb.OleDbType.VarChar);
cmd.Parameters["#Username"].Value = this.textBox1.Text;
using (OleDbDataReader dReader = cmd.ExecuteReader())
{
if (dReader.Read())
{
_wait.ShowDialog();
UserInformation.CurrentLoggedInUserLanguage = comboBox1.Text;
UserInformation.Password = (string)dReader["Password"];
isValidPassword = BCrypt.CheckPassword(this.textBox2.Text, UserInformation.Password);
if (isValidPassword)
{
System.Media.SoundPlayer sound = new System.Media.SoundPlayer(#"C:\Windows\Media\Windows Exclamation.wav");
sound.Play();
DialogResult _dialogResult = MessageBox.Show("Verified", "Congratulations", MessageBoxButtons.OK);
if (_dialogResult == DialogResult.OK)
{
UserInformation.CurrentLoggedInName = (string)dReader["ChosenName"];
UserInformation.CurrentLoggedInUser = (string)dReader["Username"];
UserInformation.CurrentLoggedInUserType = (string)dReader["UserType"];
UserInformation.CurrentLoggedInUserStore = (string)dReader["UserStore"];
this.Hide();
Choices _choices = new Choices();
_choices.ShowDialog();
this.Close();
}
}
else if (!isValidPassword)
{
System.Media.SoundPlayer sound = new System.Media.SoundPlayer(#"C:\Windows\Media\Windows Notify.wav");
sound.Play();
DialogResult _dialogResult = MessageBox.Show("Not Verified", "Warning", MessageBoxButtons.OK);
if (_dialogResult == DialogResult.OK)
{
Validation(sender, e);
RecursiveClearTextBoxes(this.Controls);
}
}
}
dReader.Close();
}
}
conn.Close();
}
}
private void button1_Click(object sender, EventArgs e)
{
CheckUserDatabase(sender, e);
}
Here is the image:
Info: this.textBox2.Text is the Password Text Box, and this.textBox1.Text is the Username Text Box, and button1_Click is the Log on button.
Note: the _wait.ShowDialog is the Wait form like the image below:
Change this:
private void button1_Click(object sender, EventArgs e)
{
CheckUserDatabase(sender, e);
}
To this:
private void button1_Click(object sender, EventArgs e)
{
_wait.ShowDialog();
CheckUserDatabase(sender, e);
}
and remove _wait.ShowDialog(); from the CheckUserDatabase() method.

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