I have two forms. One is MainForm which is an MDI parent and has a ToolStripFile that is set to enabled = false at the MainForm load, and the other form is form2 which is an MDI child and serves as my login form. If login is successful, the ToolStripFile should be enabled = true. I have this code but it doesn't work:
private void btnLogin_Click(object sender, EventArgs e)
{
MainForm mf = new MainForm();
try
{
connection.Open();
OleDbCommand command = new OleDbCommand();
command.Connection = connection;
command.CommandText = "SELECT * FROM Employees WHERE Username = #Username AND Passcode = #Passcode";
command.Parameters.AddWithValue("#Username", txtUsername.Text);
command.Parameters.AddWithValue("#Passcode", txtPassword.Text);
OleDbDataReader reader = command.ExecuteReader();
int count = 0;
while (reader.Read())
{
count = count + 1;
}
if (count == 1)
{
Employees emp = new Employees();
//emp.MdiParent = this.MdiParent;
//emp.Show();
mf.ToolStripFile.enabled = true;
this.Dispose();
}
if (count > 1)
{
MessageBox.Show("There is a duplicate in username and password.");
}
}
catch (Exception ex)
{
MessageBox.Show("ERROR: " + ex, "LOGIN");
}
finally
{
connection.Close();
}
}
You are creating a new instance of your main form. You actually need to use the instance of the current form using MDIParent property.
You can use something like this in parent form:
public bool EnableButton
{
set
{
button1.Enabled = value;
}
}
private void button1_Click(object sender, EventArgs e)
{
button1.Enabled = false;
MDIChild child = new MDIChild();
child.MdiParent = this;
child.Show();
}
In your child form, you can do something like this:
private void button1_Click(object sender, EventArgs e)
{
// if successful
(MdiParent as MDIParent).EnableButton = true;
}
Related
Aim:
I am aiming to pass value from main window i.e. the log in screen to other User Control forms.
This is MainWindow.Xaml.cs
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
}
private void CloseButton_Click(object sender, RoutedEventArgs e)
{
this.Close();
}
private void btnLogin_Click(object sender, RoutedEventArgs e)
{
string connString = ConfigurationManager.ConnectionStrings["Technical_Application.Properties.Settings.ConnectionString"].ConnectionString;
string query = "SELECT count(*) from users where username = '" + txtUsername.Text + "' and password = MD5('" + txtPassword.Password + "')";
using (var conn = new MySqlConnection(connString))
{
conn.Open();
using (var cmd = new MySqlCommand(query, conn))
{
int count = Convert.ToInt32(cmd.ExecuteScalar());
if(count == 1)
{
Dashboard dashboard = new Dashboard();
dashboard.Show();
this.Close();
}
else
{
MessageBox.Show("Username or Password unvalid", "Login Error", MessageBoxButton.OK, MessageBoxImage.Warning);
}
}
conn.Close();
}
}
}
It opens up the dashboard. I now have a ListViewMenu directed to specific User Control forms, and opens on the dashboard.
Code to open different user controls
private void ListViewMenu_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
int index = ListViewMenu.SelectedIndex;
MoveCursorMenu(index);
switch (index)
{
case 0:
GridPrincipal.Children.Clear();
GridPrincipal.Children.Add(new UserControlMain());
break;
case 1:
GridPrincipal.Children.Clear();
GridPrincipal.Children.Add(new UserControl1());
break;
default:
break;
}
}
Question:
From MainWindow the text box with name of txtUsername how can I transfer the text value to other UserControl windows?
Wouldnt it be easy to add a string property in your Dashboard class, and pass it into that - like:
Dashboard dashboard = new Dashboard();
dashboard.UserName = txtUsername.Text;
Then you can pass the same string value down to other controls. Of course, ideally, you would implement the MVVM pattern and use bindings.
I have form1 with datagridview and a button. When i click a button, a new form opens up where there is a textbox and also a button. In this textbox i can write query and with a click of a button query results are shown in form1 datagridview. The problem is that it opens up another instance of form1 , but i would like that form1 stays open the whole time and only records in datagridview are changing, according to the query input in form2. Both form1 and form2 needs to be opened and active when called.
Here is my code:
//FORM 1
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
var queryForm = new Form2();
queryForm.Show(this);
}
//FORM 2
public Form2()
{
InitializeComponent();
}
private SqlConnection Conn;
private void Form1_Load(object sender, EventArgs e)
{
Conn = new SqlConnection(#"Data Source=srvr;Initial Catalog =db; User ID =user; Password =pass");
}
private void btnExecute_Click(object sender, EventArgs e)
{
Form1 frm1 = new Form1();
frm1.Show(this);
frm1.Activate();
SqlCommand cmd = new SqlCommand();
cmd.Connection = Conn;
cmd.CommandText = txtQuery.Text;
try
{
Conn.Open();
SqlDataReader reader = cmd.ExecuteReader();
frm1.dataGridView1.Columns.Clear();
frm1.dataGridView1.Rows.Clear();
if (reader.HasRows)
{
DataTable schema = reader.GetSchemaTable();
int field_num = 0;
foreach (DataRow schema_row in schema.Rows)
{
int col_num = frm1.dataGridView1.Columns.Add(
"col" + field_num.ToString(),
schema_row.Field<string>("ColumnName"));
field_num++;
frm1.dataGridView1.Columns[col_num].AutoSizeMode =
DataGridViewAutoSizeColumnMode.AllCells;
}
object[] values = new object[reader.FieldCount];
while (reader.Read())
{
reader.GetValues(values);
frm1.dataGridView1.Rows.Add(values);
}
}
}
catch (Exception ex)
{
MessageBox.Show("Error executing command.\n" + ex.Message);
}
finally
{
Conn.Close();
}
}
Well, since you are calling Form1 frm1 = new Form1(); - what else did you expect than opens up another instance of form1 ? - Why should new Form1() not produce another instance?
You will need to get the reference of the already created Form1.
See this for example
Find the open forms in c# windows application
When you found it you can activate it for example:
var frm1 = Application.OpenForms[0];
//frm1.Show(this); <- don't need to call Show since its already open
frm1.Activate();
Also you should change your btnExecute_Click to this.
private void btnExecute_Click(object sender, EventArgs e)
{
var frm1 = Application.OpenForms[0] as Form1; //find `Form1` like you want, I only take [0]
//always create a new instance of SqlConnection here and dispose it with the using Keyword
//don't use a private field to try to keep the Connection, let the internal Connection pool handle that case
using (var con = new SqlConnection(#"Data Source=srvr;Initial Catalog =db; User ID =user; Password =pass"))
{
try
{
con.Open();
//clean up, Command/Reader with using keyword
using (var cmd = con.CreateCommand())
{
cmd.CommandText = txtQuery.Text;
using (SqlDataReader reader = cmd.ExecuteReader())
{
//read data
}
}
}
catch (Exception ex)
{
MessageBox.Show("Error executing command.\n" + ex.Message);
}
}
//should activate the `Form1` AFTER the job is done, you can consider if you only want to activate it if the previous Code didn't fail
frm1.Activate();
}
Don't really get what you are doing in your "read_data" routine.
This Code block:
frm1.dataGridView1.Columns.Clear();
frm1.dataGridView1.Rows.Clear();
if (reader.HasRows)
{
DataTable schema = reader.GetSchemaTable();
int field_num = 0;
foreach (DataRow schema_row in schema.Rows)
{
int col_num = frm1.dataGridView1.Columns.Add(
"col" + field_num.ToString(),
schema_row.Field<string>("ColumnName"));
field_num++;
frm1.dataGridView1.Columns[col_num].AutoSizeMode =
DataGridViewAutoSizeColumnMode.AllCells;
}
object[] values = new object[reader.FieldCount];
while (reader.Read())
{
reader.GetValues(values);
frm1.dataGridView1.Rows.Add(values);
}
}
Try if the following is sufficient, replace my comment "//read data" in the above code with this:
frm1.dataGridView1.AutoGenerateColumns = true; //say to automatically create columns, based on the result inside the datatable
frm1.dataGridView1.Columns.Clear();
var dataTable = new DataTable();
dataTable.Load(dataReader); //load the SqlDataReader into the DataTable
frm1.dataGridView1.DataSource = dataTable; //set the dataGridView's DataSource to the dataTable
On button click in form1, you can simply open a new instance of form2 and do your work there and on closing receive that value in form1. Or you can pass the instance of your form1 into form2 via constructor and update form1 from form2. For example:
var isFormClosed = false;
using(form1 frm = new form1())
{
// do something here
frm.ShowDialog();
isFormClosed = true;
}
Or, if you prefer to pass the reference of form1 into form2,
var isFormClosed = false;
using(form1 frm = new form1(this))
{
// do something here
frm.ShowDialog();
isFormClosed = true;
}
Here, in form2, you can simply use the passed reference of form1 to update properties or grids.
I'm currently making a windows form login system and I've worked out how to set up a general everyone can see the main page system but for the admin i want it to open a new form (form3) which will contain customer orders.
i need it to open up from Login Button.Click just like form2 opens to show the store page for generalised users. i don't have a column in my table for user roles either.
I've tried if else statements and run into issues with bools not excepting strings etc.
using System;
using System.Data;
using System.Windows.Forms;
using MySql.Data;
using MySql.Data.MySqlClient;
namespace Aliena_Store
{
public partial class Form1 : Form
{
//string ConnectionState = "";
public Form1()
{
InitializeComponent();
}
MySqlConnection connection = new MySqlConnection("server=localhost;user=root;database=Aliena_Store;port=3306;password=Blackie");
MySqlDataAdapter adapter;
DataTable table = new DataTable();
private void UsernameLogin_TextChanged(object sender, EventArgs e)
{
}
private void PasswordLogin_TextChanged(object sender, EventArgs e)
{
}
private void LoginButton_Click(object sender, EventArgs e)
{
adapter = new MySqlDataAdapter("SELECT `username`, `password` FROM `User_Details` WHERE `username` = '" + UsernameLogin.Text + "' AND `password` = '" + PasswordLogin.Text + "'", connection);
adapter.Fill(table);
var usernameSaved = UsernameLogin.Text;
var passwordSaved = PasswordLogin.Text;
Panel panel1 = new Panel();
if (table.Rows.Count <= 0)
{
panel1.Height = 0;
var result = MessageBox.Show("Username/Password Are Invalid or does not exist. Please sign up or retry your details");
}
else
{
panel1.Height = 0;
this.Hide();
if (table.Rows.Count >= 0)
{
Form nextForm;
var result = MessageBox.Show("Login successful...Now logging in");
this.Hide();
object user = UsernameLogin.Text;
object password = PasswordLogin.Text;
if (user = "root" & password = "Pa$$w0rd")
{
nextForm = new Form3();
}
else
{
nextForm = new Form2();
}
nextForm.ShowDialog();
}
//Form2 f2 = new Form2();
//f2.ShowDialog();
//if login is successful needs to lead to another screen - if matches my account standard store screen or make root account just for the admin page
}
table.Clear();
}
private void EmailSignUp_TextChanged(object sender, EventArgs e)
{
}
private void UsernameSignUp_TextChanged(object sender, EventArgs e)
{
}
private void PasswordSignUp_TextChanged(object sender, EventArgs e)
{
}
private void SignUpButton_Click(object sender, EventArgs e)
{
//connection.Open();
string Query = "insert into User_Details (Email,Username,Password) values('" + this.EmailSignUp.Text + "', '" + this.UsernameSignUp.Text + "','" + this.PasswordSignUp.Text + "');";
//string insertQuery = "INSERT INTO User_Details(Email,Username,Password)VALUES('" + EmailSignUp.Text + "','" + UsernameSignUp.Text + "'," + PasswordSignUp.Text + ")";
MySqlCommand command = new MySqlCommand(Query,connection);
try
{
if (command.ExecuteNonQuery() == 1)
{
MessageBox.Show("Data Inserted");
connection.Close();
}
else
{
MessageBox.Show("Data Not Inserted");
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
connection.Close();
}
}
}
}
A couple of things.
You need a User object in your application that stores user properties. This object can have an IsAdmin property that you can use later in your code.
Alternately, if you don't want to create and maintain a User object, you make another call to the database to see whether or not the user is an admin and store the result local to your method.
You then instantiate Form3 instead of Form2 based on whether or not the user is an admin.
Form nextForm;
var result = MessageBox.Show("Login successful...Now logging in");
this.Hide();
if (user.IsAdmin) {
nextForm = new Form3();
} else {
nextForm = new Form2();
}
nextForm.ShowDialog();
PS: I hope you are not storing passwords in plain text in your database like it seems you are.
I'm beginner in C#. I have some buttons which are disabled by default in the main form. After the user signs in I want them to be enabled and available for the user to work with. It's kind of an access modifier.
The buttons are in the main form and the login form is within another form. After user pressed a login button (checking the username and password) i want to enable those button in the main form.below is my code
private void btnLogic_Click(object sender, EventArgs e)
{
FormSettingLogic f2 = new FormSettingLogic();
f2.Owner = this;
f2.Show();
}
private void btnAddFile_Click(object sender, EventArgs e)
{
FormLogin fl = new FormLogin();
fl.Owner = this;
....
....
}
private void btnLoadManteg_Click(object sender, EventArgs e)
{
Form_LoadMantegh f6 = new Form_LoadMantegh();
f6.Owner = this;
f6.Show();
}
and user's login code
public FormLogin()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
String abc;
try
{
sqlConnection1.Open();
SqlCommand cmd = new SqlCommand("select * from [Users] where userName=#uName and password = #Pass ", sqlConnection1);
SqlDataAdapter sda;
sda = new SqlDataAdapter();
sda.SelectCommand = cmd;
sda.SelectCommand.Parameters.AddWithValue("#uName", txtUname.Text);
sda.SelectCommand.Parameters.AddWithValue("#Pass", txtpass.Text);
abc =Convert.ToString (cmd.ExecuteScalar()); //execute the query and get the user Id and put it in abc variable
DataTable dt = new DataTable();
sda.Fill(dt);
sqlConnection1.Close();
if (dt.Rows.Count == 0)
{
MessageBox.Show("Username or Password is incorrect!");
}
else
{
this.Hide();
//MessageBox.Show(abc);
sendID.send = abc;
(this.Owner as Form_Main).btnAddFile.Enabled = true;
(this.Owner as Form_Main).btnLogic.Enabled = true;
}
}
catch(Exception err)
{
MessageBox.Show(err.Message);
}
Form_Main_load code :
private void Form_Main_Load(object sender, EventArgs e)
{
btnLogic.Enabled = false;
btnAddFile.Enabled = false;
btnLoadManteg.Enabled = false;
}
and the Error is: "Object reference not set to an instance of an object"
if user pass the login set userName but user can not pass the login set userName to null
public Form1()
{
InitializeComponent();
button1.Visible = false;
}
public void AfterLoginMethod()
{
if (userName!=null)//You can use another control like userId > 0 ...
button1.Visible = true;
}
Here is the my c# application, it's a pop up ,i want to know how add cache clean method to this code.
i want to include a cache clean coding to clean cache in this program and minimize the ram
namespace SmartAlert
{
public partial class Form2 : Form
{
static String maxValue = "1";
static int checkNewRecordTime =8;
static int frameVisibilityTime = 20;
private const int CP_DISABLE_CLOSE_BUTTON = 0x200;
System.Windows.Forms.Timer hideTime;
public Form2()
{
InitializeComponent();
checkNewRecordTimer();
checkNewRecord();
}
// Method to disable form close button \\
protected override CreateParams CreateParams
{
get
{
CreateParams cp = base.CreateParams;
cp.ClassStyle = cp.ClassStyle | CP_DISABLE_CLOSE_BUTTON;
return cp;
}
}
protected override void OnLoad(EventArgs e)
{
// Code for set the screen location \\
var screen = Screen.FromPoint(this.Location);
this.Location = new Point(screen.WorkingArea.Right - this.Width, screen.WorkingArea.Bottom - this.Height);
base.OnLoad(e);
}
private void Form2_Load(object sender, EventArgs e)
{
}
// Database record's checking method \\
// 2
public void checkNewRecord()
{
try {
var connectionString = ConfigurationManager.ConnectionStrings["conn"].ConnectionString;
SqlConnection scon = new SqlConnection(connectionString);
String cost_code = ConfigurationManager.AppSettings["costCenter"].ToString();
scon.Open();
SqlCommand smd = new SqlCommand();
DateTime d1 = DateTime.Now;
string sqlFormattedDate = d1.Date.ToString("yyyy-MM-dd");
//** query for check and get the last enterd record **\\
smd.CommandText = "select max(OrdM_No) as M_id from FOOrderMaster where OrdM_Staff ='" + cost_code + "' and OrdM_Date ='" + sqlFormattedDate + "' ";
smd.Connection = scon;
SqlDataReader reader = smd.ExecuteReader();
reader.Read();
string mx_id = reader["M_id"].ToString();
reader.Close();
if (maxValue != mx_id)
{
maxValue = mx_id;
popup_Window(mx_id);
this.Show();
frameHideTimer();
}
scon.Close();
}
catch (SqlException)
{
}
catch (Exception)
{
}
}
// Retriving Database record's checking and sending to form method \\
// 3
public void popup_Window(String mx_id)
{
try
{
var connectionString = ConfigurationManager.ConnectionStrings["conn"].ConnectionString;
SqlConnection scon1 = new SqlConnection(connectionString);
scon1.Open();
//** query for get the data of last enterd record **\\
SqlCommand smd1 = new SqlCommand();
smd1.CommandText = "SELECT f.OrdM_No,f.OrdM_BillNo,f.OrdM_Table,f.OrdM_Date,d.OrdD_Price FROM FOOrderMaster f inner join FOOrderDetail d on f.OrdM_No = d.OrdM_No WHERE f.OrdM_No = '" + mx_id + "'";
smd1.Connection = scon1;
SqlDataReader reader12 = smd1.ExecuteReader();
reader12.Read();
if (reader12.HasRows)
{
label8.Text = reader12["OrdM_BillNo"].ToString();
label9.Text = reader12["OrdD_Price"].ToString();
label7.Text = reader12["OrdM_Table"].ToString();
string nm = reader12["OrdM_Date"].ToString();
DateTime dm = Convert.ToDateTime(nm);
string df = dm.Date.ToString("yyyy-MM-dd");
label6.Text = df.ToString();
}
scon1.Close();
}
catch (SqlException)
{
}
catch (Exception)
{
}
}
// timer for check new record method \\
// 1
public void checkNewRecordTimer()
{
System.Windows.Forms.Timer t = new System.Windows.Forms.Timer();
t.Interval = 1000*checkNewRecordTime; // specify interval time as you want
t.Tick += new EventHandler(timer_Tick);
t.Start();
}
void timer_Tick(object sender, EventArgs e)
{
checkNewRecord();
}
// timer for hidden the form \\
public void frameHideTimer()
{
hideTime = new System.Windows.Forms.Timer();
hideTime.Interval = 1000*frameVisibilityTime; // specify interval time as you want
hideTime.Tick += new EventHandler(hideTimer_Tick);
hideTime.Start();
}
void hideTimer_Tick(object sender, EventArgs e)
{
this.Hide();
hideTime.Stop();
}
private void button1_Click(object sender, EventArgs e)
{
var fm3 = new Form3();
fm3.Show();
}
private void Form2_Move(object sender, EventArgs e)
{
}
private void notifyIcon1_MouseDoubleClick(object sender, MouseEventArgs e)
{
var fm3 = new Form3();
fm3.Show();
notifyIcon1.Visible = true;
}
}
}
please help me with this