I am trying to create a function GetUserID() which returns the userID, which I have inserted into a label so I can use it in other forms.
But when I try to convert the label to int32 the label always seems to be empty. I think its because of where the function is placed in my code.
See:
private void Loginbtn_Click(object sender, EventArgs e)
{
var LoginFunction = new LoginFunction();
var DataTable = new DataTable();
DataTable = LoginFunction.Login(Usernametxt.Text.Trim(), Passwordtxt.Text.Trim());
int UserID = Convert.ToInt32(DataTable.Rows[0]["USER_ID"]);
if (DataTable.Rows.Count == 1)
{
CalculatorMain calculatorMain = new CalculatorMain();
MainMenu mainMenu = new MainMenu();
UserIDlbl.Text = Convert.ToString(UserID);
MessageBox.Show("ID = " + UserID);
this.Hide();
mainMenu.Show();
}
else
{
MessageBox.Show("You entered the wrong username or password");
}
}
public int GetUserID()
{
int UserID;
if (Int32.TryParse(UserIDlbl.Text, out UserID))
{
UserID = Convert.ToInt32(UserIDlbl.Text);
}
else
{
MessageBox.Show("Error, Label for UserID could not be parsed");
}
return UserID;
}
I'm not sure where else I can put this function to get it to work.
Here is the code to call the function which is used in a separate form.
private void WorkoutHistoryForm_Load(object sender, EventArgs e)
{
Login login = new Login();
int UserId = login.GetUserID();
this.sETSTableAdapter.Fill(this.gymDataSet.SETS, UserId);
}
I keep thinking there must be a better way to do this instead of storing the UserID in a label but I'm not sure how.
I would create a public class with a public field to store the UserID.
For example. let's say you have the UserID in an int variable as you have described. Now let's say you have created a public static class called Common defined with a public static field of type int called ID.
You can now store the UserID in the static field of the class:
Common.ID = UserID
Later, when you want to access the UserID from some other form, just do this:
string UserID = Common.ID
Easy peasey.
Of course, you don't need to do this in a separate class... your form itself is a class, and you can create your public field there, and call it like
Form1.UserID
Or whatever the name of your original form is where you captured the UserID...
Related
I'll give you an example of what I want to see, but I can't do it in any way:
public class User
{
private string name;
private int age;
private int id;
public User(string name, int age, int id)
{
this.name = name;
this.age = age;
this.id = id;
}
}
private void Button_Click(object sender, RoutedEventArgs e)
{
string name = tb1.Text;
int age = Convert.ToInt32(tb2.Text);
int id = Convert.ToInt32(tb3.Text);
User ??? = new User(name,age,id);
}
??? - what should I put in the name? After all, I need to create a new object each time, respectively, with different names. How to do it?
You best create a list (List<User>) (or other type of collection) to which you can add new elements:
private readonly List<User> users = new List<User>();
private void Button_Click(object sender, RoutedEventArgs e)
{
string name = tb1.Text;
int age = Convert.ToInt32(tb2.Text);
int id = Convert.ToInt32(tb3.Text);
users.Add(new User(name,age,id));
}
This list could be defined the class containing Button_Click() or somewhere else depending on what needs to be done with the created User instances.
Access of the List elements:
To then get the third user creaded, use
user someUser = users[2];
To get the first John in the users list, use
user john = users.First(x => x.name != "John");
To get all Johns, use
List<user> johns = users.Where(x => x.name != "John");
ok guys/girls, i am new to programming and have a question. i created one winform for insert data into sql server..now i want to use that same form to update data..i already did that with constructor overload and chaining, and it is work!
on main form frmEmployees i have two buttons, btnAddEmployee and btnUpdateEmployee, i also have employeeID (i get id from the datagrid) and a bool variable called 'isEditMode =true', now when i click btnUpdateEmployee i am sending EmployeeID, and isEditMode values to overloaded constructor..and frmAddEmployee opens..there i have global private variabables employeeID and bool isEditmode..and then i set their values via overloaded constructor, and that is work, BUT..when i click btnAddEmployee i am not sending employeeID and isEditMode values..and i come up with unused variables when adding employee..
private int employeeID;
private bool isEditMode;
public frmAddEmployee()
{
InitializeComponent();
this.AutoValidate = AutoValidate.Disable;
}
public frmAddEmployee(int employeeID, bool isEditMode): this()
{
this.employeeID = employeeID;
this.isEditMode = isEditMode;
}
You haven't showed us a lot of code but i will give you good example of how i am handing communication between program and SQL Database.
So first of all I create class for each object. In your example i see you have Employee so i would create class with few information (variables) about each of my employee and functions i want to have for them. So class would look something like this:
public class Employee
{
static string databaseString = "";
public int Id { get { return _Id; } } //This is property
public string Name { get { return _Name; } set { _Name = value; } } //This is property
private int _Id; //This is private variable used by property
private string _Name; //This is private variable used by property
public Employee()
{
//Constructor used to create empty object
}
public Employee(int Id)
{
try
{
using (SqlConnection con = new SqlConnection(databaseString))
{
con.Open();
using (SqlCommand cmd = new SqlCommand("SELECT NAME FROM Employee WHERE ID = #ID", con))
{
cmd.Parameters.AddWithValue("#ID", Id);
SqlDataReader dr = cmd.ExecuteReader();
//I am usin IF(dr.Read()) instead of WHILE(dr.Read()) since i want to read only first row.
if (dr.Read())
{
this._Id = Id;
this._Name = dr[0].ToString();
}
else
{
System.Windows.Forms.MessageBox.Show("There was no Employee with that ID in database!");
}
}
}
}
catch(SqlException ex)
{
System.Windows.Forms.MessageBox.Show(ex.ToString());
}
}
public void Save(bool showMessage)
{
using (SqlConnection con = new SqlConnection(databaseString))
{
con.Open();
using (SqlCommand cmd = new SqlCommand("UPDATE Employee SET NAME = #N WHERE ID = #ID", con))
{
cmd.Parameters.AddWithValue("#N", this._Name);
cmd.Parameters.AddWithValue("#ID", this._Id);
cmd.ExecuteNonQuery();
if (showMessage)
System.Windows.Forms.MessageBox.Show("Employee saved!");
}
}
}
public static void Create(string Name, bool showMessage = true)
{
using (SqlConnection con = new SqlConnection(databaseString))
{
con.Open();
using (SqlCommand cmd = new SqlCommand("INSERT INTO Employee (ID, NAME) VALUES (COALESCE(MAX(ID), 1), #NAME)", con))
{
cmd.ExecuteNonQuery();
if (showMessage)
System.Windows.Forms.MessageBox.Show("New Employee created!");
}
}
}
}
Now when i have my class i can call it 2 ways:
Employee emp = new Employee(); //This will create empty employee object
Employee emp1 = new Employee(1); //This will create employee object and will load employees data from database where employees id == 1
Also what i can do is:
Employee.Create("SomeName"); //Calling public static method from Employee class. Doesn't require you to create object for static methods
or if i have loaded employee and want to change it's name and then save i would do it like this:
Employee emp2 = new Employee(1); //Created and loaded emp from database
emp2.Name = "Changed Name";
emp2.Save(); //Called public method.
So now if you have form which display one employee it would look like this:
public partial class Form1 : Form
{
private Employee emp;
public Form(int EmployeeID)
{
InitializeComponents();
//Creating new object of Employee but with constructor that will automatically load variables into it.
emp = new Employee(EmployeeID);
//Checking to see if employee is loaded since if there was no employee with given ID it would return null
if(emp.Id == null || < 1)
{
DialogResult dr = MessageBox.Show("Employee doesn't exist. Do you want to create new one?", "Confirm", MessageBoxButtons.YesNo);
if(dr == DialogResult.No)
{
//User doesn't want to create new employee but since there is no employee loaded we close form
this.Close();
}
else
{
Employee.Create("New Employee");
MessageBox.Show("New employee created");
//Here we need to load this employee with code like emp = new Employee(newEmployeeId);
//To get new employee id you have 2 options. First is to create function inside Employee class that will Select MAX(ID) from Employee and return it. (bad solution)
//Second solution is to return value upon creating new employee so instead function `public static void Create()` you need to have `public static int Create()` so it returns newly created ID of new row in SQL database. I won't explain it since you are new and it will be too much information for now. You will easily improve code later. For now you can use Select Max(id) method
}
}
textBox1.Text = emp.Id;
textBox2.Text = emp.Name;
}
private void OnButton_Save_Click(object sender, EventArgs e)
{
DialogResult dr = MessageBox.Show("Do you really want to save changes?", "Save", MessageBoxButtons.YesNo);
if(dr == DialogResult.Yes)
{
emp.Save();
}
else
{
//Here create private Reload function inside form that will do emp = Employee(emp.Id) and then set UI again.
}
}
private void OnButton_CreateNewEmployee_Click(object sender, EventArgs e)
{
Employee.Create("New Employee");
int newEmpID = something; //As i said up create method to select MAX ID or update SQL inside Create function to return newly created ID
//I am using using since after form closes it automatically disposes it
using(Form1 f = new Form1(newEmpID))
{
f.showDialog()
}
this.Close();
}
}
I am new to C# and I am working on a project for my studies and I have multiple logins an Administrator and Teacher. This project has multiple winforms the 2 I am needing help with is my Login and the Main form after the user logs in.
I have already created the logins and they work but I need to disable a button called btnMarks int he Main form the Administrator cannot have access to this button.
I have tried if statements but I can't seem to make it work. I am using radio buttons for logins as well as the Administrator and Teachers logins have their own tables in the database. I can only use Entities not SQLconnections it is part of the project for my studies.
Please help
Below is my user login form code.
private void btnLogin_Click(object sender, EventArgs e)
{
//A check to make sure both fields have an entry
if(txtUsername.Text == "" || txtPassword.Text == "")
{
MessageBox.Show("Please provide a Username and Password!");
return;
}
//This is to call the boolean radiobuttons are checked
radioButtons();
//Teachers login
if (rbTeachers.Checked)
{
int Username = Convert.ToInt32(txtUsername.Text);
SchoolDBEntities db = new SchoolDBEntities();
var tid = from t in db.Teachers
where t.TID == Username
&& t.Password == txtPassword.Text
select t;
if (tid.Any())
{
MessageBox.Show("You are now logged in as a Teacher!");
this.Hide();
Main tss = new Main();
tss.Show();
}
else
{
MessageBox.Show("Incorrect Username or Password!");
}
}
//Administrator login
if (rbAdmin.Checked)
{
int Username = Convert.ToInt32(txtUsername.Text);
SchoolDBEntities db = new SchoolDBEntities();
var aid = from a in db.Administrators
where a.AID == Username
&& a.Password == txtPassword.Text
select a;
if (aid.Any())
{
MessageBox.Show("You are now logged in as Administrator");
this.Hide();
Main tss = new Main();
tss.Show();
}
else
{
MessageBox.Show("Incorrect Username or Password");
}
}
}
Below is my Main form, I need the btnMarks button disabled for Administrators.
I am unsure where to put the code to disable this button as well. If I could be able to call the radio button from the login form please show me how.
public partial class Main : Form
{
public Main()
{
InitializeComponent();
}
private void Main_Load(object sender, EventArgs e)
{
}
private void btnMarks_Click(object sender, EventArgs e)
{
frmStudentMarks marks = new frmStudentMarks();
marks.ShowDialog();
}
Thanks
I would recommend you making something like SessionManagement object to manage current session ( logged user, user rights etc. ).
public static class SessionManagement
{
static UserEntity sessionUser = null;
public static void LoggedAs(UserEntity user)
{
sessionUser = user;
}
// other methods/fields to manage session
}
After doing this you can just set session for currently logged user :
var tid = from t in db.Teachers
where t.TID == Username
&& t.Password == txtPassword.Text
select t;
SessionManagement.LoggedAs((UserEntity)tid); // make some explicit operators or something.
Now you have full control over who is logged in and you can check it's rights so all you have to do is to check it after InitializeComponent() method call :
public Main()
{
InitializeComponent();
btnMarks.Enabled = !SessionManagement.CurrentUser.IsAdministrator;
}
EDIT:
You've asked if there's something else you should do for this code to make it works. Answer is yes. This answer is basically a scheme for you to work something out. But since it's not an easy thing to do I'll explain it in somewhat more details.
Firstly, you have 2 types of Entity: Teacher and Administrator and you need to make one "unified" entity ( I named it UserEntity ). This unified entity should be convertible from both Teacher and Administrator entity.
My recommendation in code :
public class UserEntity
{
string _username;
public string Username
{
get { return _username; }
}
bool _isAdministrator;
public bool IsAdministrator
{
get { return _isAdministrator; }
}
public UserEntity(Administrator entity)
{
_isAdministrator = true;
_username = entity.AID;
}
public UserEntity(Teacher entity)
{
_isAdministrator = false;
_username = entity.TID;
}
public static explicit operator UserEntity(Administrator entity)
{
return new UserEntity(entity);
}
public static explicit operator UserEntity(Teacher entity)
{
return new UserEntity(entity);
}
}
Now you can do somehting like UserEntity userEntity = (UserEntity)teacher;
Next thing to do is to update SessionManagement by adding new method into it :
public static void LoggedAs(UserEntity entity)
{
if(sessionUser != null)
throw new InvalidOperationException("Cannot be logged 2 times with the same session");
sessionUser = entity;
}
And a property :
public static UserEntity CurrentUser
{
get { return sessionUser; }
}
Now all you have to do is to combine all of these into one huge chunk of code :
private void btnLogin_Click(object sender, EventArgs e)
// parts of your code till this line :
SchoolDBEntities db = new SchoolDBEntities();
var tid = from t in db.Teachers
where t.TID == Username
&& t.Password == txtPassword.Text
select t;
Teacher teacher = tid.FirstOrDefault();
if(teacher != null)
{
SessionManagement.LoggedAs((UserEntity)teacher);
}
// do the same with Administrator
Now since SessionManagement is static object you can use it everywhere inside your application and it will persist with all stored data meaning you can use :
public Main()
{
InitializeComponent();
btnMarks.Enabled = !SessionManagement.CurrentUser.IsAdministrator;
}
You need to maintain a static class for that in which you can add that the current user's type.
Kindly go through the following url
https://stackoverflow.com/a/14599474/1526972
The command button, by default, has a public access level so you can access and disable it from login form before to call the Show() method in this way:
tss.yourButtonName.Enabled = false;
Hope this help.
Christian
I would like to point to a row.
Get the Oid(the parameter I want to pass).
When I click a button on the ribbon. It will open MifarePasswordForm. I would like to pass Oid to MifarePasswordForm so that the Oid can be saved in Mifare Card but I'm stuck at getting the Oid. So far, this is what I've got.
public void barButtonItem1_ItemClick()
{
staff entity = gridView.GetRow(gridView.GetSelectedRows()[0]) as staff;
entity.Oid;
MifarePasswordForm modalForm = new MifarePasswordForm();
modalForm.ShowDialog();
RefreshData();
}
This is my password form.
public MifarePasswordForm(int _iD)
{
InitializeComponent();
int iD = _iD;
}
Updated code
public void barButtonItem1_ItemClick()
{
staff entity = gridView.GetRow(gridView.GetSelectedRows()[0]) as staff;
MifarePasswordForm modalForm = new MifarePasswordForm(entity.Oid);
modalForm.ShowDialog();
RefreshData();
}
public MifarePasswordForm(int _iD)
{
InitializeComponent();
int iD = _iD;
textBox1.Text += iD;
}
What you can do is, pass your parameter to form in the constructor itself OR, make a public property and access it after creating formInstance and assign it your designated value.
e.g.
MifarePasswordForm modalForm = new MifarePasswordForm(entity.Oid);
modalForm.ShowDialog();
So I have a simple User Class:
public class User
{
public string id, name, email, image;
public User (IFBGraphUser user)
{
id = user.GetId ();
name = user.GetName ();
GetEmail ();
}
private void GetEmail()
{
FBRequestConnection.StartWithGraphPath("/me", null, "GET", delegate(FBRequestConnection connection, NSObject result, NSError error) {
var me = (FBGraphObject)result;
this.email = me["email"].ToString();
});
}
}
But I need to get the users email from Facebook. My Facebook request has a delegate and when I try to assign the email field inside the delegate, the email field remains null. How can I go about getting the email into the email field from the delegate?
Its not a problem with the facebook result, ive tried this.email = "test"; and it was still null when I went to access it.
In this Code i am setting a class level field's value and accessing it outside of delegate so this might help you, see the below given code:-
public delegate void delgJournalBaseModified(string a);
public class User
{
public string id, name, email, image;
public User(string uid,string uName)
{
id = uid;
name = uName;
Console.WriteLine(this.name);
Console.WriteLine(this.email);
GetEmail();
}
private void GetEmail()
{
set(delegate(string d)
{
this.email = d;
});
}
private void set(delgJournalBaseModified delgJournalBaseModified)
{
delgJournalBaseModified.Invoke("value is set");
Console.WriteLine(this.email);
}
}
and call like this in main method or anywhere you like..
User a1 = new User("123", "dev");
Console.WriteLine(a1.email);
now if you will the console "value is set" is being print twice.
Thanks
Devendra