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.
Related
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 creating a school project. One of my ideas is to after the Login Form the Main Form will show on a label the user connected and the RM (user code basically), but i don't know how to get the Username and RM from the Login Screen and get the RM from the database.
Login Screen Code:
public partial class Login : Form
{
public Login()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
SqlConnection con = new SqlConnection(#"Data Source=ROCHA-PC\SQLSERVER2014;Initial Catalog=Usuarios;Integrated Security=True");
SqlDataAdapter sda = new SqlDataAdapter("Select Count(*) from users where usuario = '" + textBox1.Text + "' AND senha = '" + textBox2.Text + "'" , con);
DataTable dt = new DataTable();
sda.Fill(dt);
if (dt.Rows[0][0].ToString() == "1")
{
this.Hide();
frmTelaInicial nform = new frmTelaInicial();
nform.Show();
}
else
{
MessageBox.Show("Erro ao logar");
}
}
private void button2_Click(object sender, EventArgs e)
{
Application.Exit();
}
How can I get the current user connected and show it on the label?
Go to the constructor of the main window and add the parameters you want for example
step 1)
here pass the parameters you want
frmTelaInicial nform = new frmTelaInicial(LoggedUseName,RM);
step 2)
at the constructor of the frmTelaInicial add the two parameters like below
public frmTelaInicial(string LoggedUserName,string RM)
{
//here you have the passed values
}
step 3)
add two labels on the frmTelaInicial window and update their values with the passed values LoggedUserName and RM
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;
}
Hello all just an update, I am still facing the issues of getting the chart to display the correct number of records. I have discovered where the chart is currently getting it's numbers from however it makes no sense as to why it is using those numbers. It is from a column in the database called "mpm_code" however I have never specified for the chart to use those numbers. Here are the numbers in the database:
Here is the chart
And here is my code:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Data.OleDb;
namespace RRAS
{
public partial class formRRAS : Form
{
public OleDbConnection DataConnection = new OleDbConnection();
string cmbRFR_item;
public formRRAS()
{
InitializeComponent();
}
//When the form loads it sets the intial combo box RFR item to null
private void formRRAS_Load(object sender, EventArgs e)
{
// TODO: This line of code loads data into the 'database1DataSet.tblReject_test' table. You can move, or remove it, as needed.
this.tblReject_testTableAdapter.Fill(this.database1DataSet.tblReject_test);
cmbRFR.SelectedItem = "";
this.AcceptButton = btnSearch;
}
//AddRFR method, called in the NewRFRPopup
public void AddRFR(object item)
{
cmbRFR.Items.Add(item);
}
private void change_cmbSubRFR_items()
{
cmbSubRFR.Items.Clear();//Clear all items in cmbSubRFR comboBox.
switch (cmbRFR_item)//Adding your new items to cmbSubRFR.
{
case "":
cmbSubRFR.Items.Add("");
cmbSubRFR.Text = "";
break;
case "POSITIONING":
cmbSubRFR.Items.Add("");
cmbSubRFR.Items.Add("Anatomy cut-off");
cmbSubRFR.Items.Add("Rotation");
cmbSubRFR.Items.Add("Obstructed view");
cmbSubRFR.Items.Add("Tube or grid centering");
cmbSubRFR.Items.Add("Motion");
cmbSubRFR.Text = "";
break;
case "ARTEFACT":
cmbSubRFR.Items.Add("");
cmbSubRFR.Items.Add("ARTEFACT");
cmbSubRFR.Text = "ARTEFACT";
cmbSubRFR.Text = "";
break;
case "PATIENT ID":
cmbSubRFR.Items.Add("");
cmbSubRFR.Items.Add("Incorrect Patient");
cmbSubRFR.Items.Add("Incorrect Study/Side");
cmbSubRFR.Items.Add("User Defined Error");
cmbSubRFR.Text = "";
break;
case "EXPOSURE ERROR":
cmbSubRFR.Items.Add("");
cmbSubRFR.Items.Add("Under Exposure");
cmbSubRFR.Items.Add("Over Exposure");
cmbSubRFR.Items.Add("Exposure Malfunction");
cmbSubRFR.Text = "";
break;
case "TEST IMAGES":
cmbSubRFR.Items.Add("");
cmbSubRFR.Items.Add("Quality Control");
cmbSubRFR.Items.Add("Service/Test");
cmbSubRFR.Text = "";
break;
}
}
private void cmbRFR_SelectedIndexChanged(object sender, EventArgs e)
{
if (cmbRFR_item != cmbRFR.SelectedItem.ToString())//This controls the changes in cmbRFR about selected item and call change_cmbSubRFR_items()
{
cmbRFR_item = cmbRFR.SelectedItem.ToString();
change_cmbSubRFR_items();
}
}
//The code for the button that closes the application
private void btnSearch_Click(object sender, EventArgs e)
{
//This creates the String Publisher which grabs the information from the combo box on the form.
//Select and Dataconnection are also defined here.
string Department = String.IsNullOrEmpty(txtDepartment.Text) ? "%" : txtDepartment.Text;
string Start_Date = String.IsNullOrEmpty(txtStart.Text) ? "%" : txtStart.Text;
string End_Date = String.IsNullOrEmpty(txtEnd.Text) ? "%" : txtEnd.Text;
string Anatomy = String.IsNullOrEmpty(txtAnatomy.Text) ? "%" : txtAnatomy.Text;
string RFR = String.IsNullOrEmpty(cmbRFR.Text) ? "%" : cmbRFR.Text;
string Comment = String.IsNullOrEmpty(cmbSubRFR.Text) ? "%" : cmbSubRFR.Text;
string Select = "SELECT * FROM tblReject_test WHERE department_id LIKE '" + Department + "'" + "AND body_part_examined LIKE'" + Anatomy + "'" + "AND study_date LIKE'" + Start_Date + "'" + "AND study_date LIKE'" + End_Date + "'" + "AND reject_category LIKE'" + RFR + "'" + "AND reject_comment LIKE'" + Comment + "'";
//DataConnection connects to the database.
string connectiontring = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=|DataDirectory|\\Database1.mdb";
DataConnection = new OleDbConnection(connectiontring);
//The DataAdapter is the code that ensures both the data in the Select and DataConnection strings match.
OleDbDataAdapter rdDataAdapter = new OleDbDataAdapter(Select, DataConnection);
try
{
//It then clears the datagridview and loads the data that has been selected from the DataAdapter.
database1DataSet.tblReject_test.Clear();
rdDataAdapter.Fill(this.database1DataSet.tblReject_test);
}
catch (OleDbException exc)
{
System.Windows.Forms.MessageBox.Show(exc.Message);
}
} //End of Search button
//Temporary button thats loads the chart when clicked
private void btnLoadChart_Click(object sender, EventArgs e)
{
charRejections.Series["RFR"].Points.Clear();
{
string connectiontring = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=|DataDirectory|\\Database1.mdb";
DataConnection = new OleDbConnection(connectiontring);
try
{
int count = database1DataSet.Tables["tblReject_test"].Rows.Count;
DataConnection.Open();
OleDbCommand command = new OleDbCommand();
command.Connection = DataConnection;
string query = "SELECT COUNT(*) as count, reject_category FROM tblReject_test GROUP BY reject_category";
command.CommandText = query;
OleDbDataReader reader = command.ExecuteReader();
while (reader.Read())
{
charRejections.Series["RFR"].Points.AddXY(reader["reject_category"].ToString(), reader[count]);
}
DataConnection.Close();
}
catch (Exception ex)
{
MessageBox.Show("Error " + ex);
}
}
} //end of load chart button
//These buttons are all from the file menu bar
//A simple button that closes the application
private void exitToolStripMenuItem_Click(object sender, EventArgs e)
{
this.Close();
}
//This button loads the NewRFRPopup form
private void addRFRToolStripMenuItem_Click(object sender, EventArgs e)
{
NewRFRPopup popup = new NewRFRPopup(this);
popup.ShowDialog();
}
private void printChartToolStripMenuItem_Click(object sender, EventArgs e)
{
charRejections.Printing.PrintDocument.DefaultPageSettings.Landscape = true;
charRejections.Printing.PrintPreview();
}
//End of file menu bar
//These buttons change the format of the chart
private void btnPie_Click(object sender, EventArgs e)
{
this.charRejections.Series["RFR"].ChartType = System.Windows.Forms.DataVisualization.Charting.SeriesChartType.Pie;
}
private void btnBar_Click(object sender, EventArgs e)
{
this.charRejections.Series["RFR"].ChartType = System.Windows.Forms.DataVisualization.Charting.SeriesChartType.Column;
}
private void btnSideways_Click(object sender, EventArgs e)
{
this.charRejections.Series["RFR"].ChartType = System.Windows.Forms.DataVisualization.Charting.SeriesChartType.Bar;
}
private void btnLine_Click(object sender, EventArgs e)
{
this.charRejections.Series["RFR"].ChartType = System.Windows.Forms.DataVisualization.Charting.SeriesChartType.Line;
}
//end of chart formatting
}
}
The Issue has been sorted thanks to a friend of mine. This relates to the code that TaW posted the other day. Thanks for everyone's time and suggestions. The fixed code is below:
private void btnLoadChart_Click(object sender, EventArgs e)
{
charRejections.Series["RFR"].Points.Clear();
{
string connectiontring = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=|DataDirectory|\\Database1.mdb";
DataConnection = new OleDbConnection(connectiontring);
try
{
DataConnection.Open();
OleDbCommand command = new OleDbCommand();
command.Connection = DataConnection;
string query = "SELECT COUNT(reject_category) as reject, reject_category FROM tblReject_test GROUP BY reject_category";
command.CommandText = query;
OleDbDataReader reader = command.ExecuteReader();
while (reader.Read())
{
charRejections.Series["RFR"].Points.AddXY(reader["reject_category"].ToString(), reader["reject"].ToString());
}
DataConnection.Close();
}
catch (Exception ex)
{
MessageBox.Show("Error " + ex);
}
}
}//end of load chart button
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;
}