Can't call upon objects, not sure why - c#

So I have a form with 3 buttons in it, "Add Users", "Delete Users", "Change Password". When you click on one of those buttons I don't want a new form to appear, but instead I want the current for to change and show new textboxes & buttons. The problem is that when I code these textboxes and buttons, I can't call upon them as objects in private void BtnAddUser_Click(object sender, Routed EventArgs e).
Can someone please explain what I'm doing wrong?
There error's that I'm getting is that: The name 'txtUsername', 'pbxPassword' and 'cboRangen' do not exist in the current context.
public admin()
{
InitializeComponent();
}
private void btnAddUsers_Click(object sender, RoutedEventArgs e)
{
// Buttons verbergen
btnAddUsers.Visibility = Visibility.Hidden;
btnDeleteUsers.Visibility = Visibility.Hidden;
btnChangePasswords.Visibility = Visibility.Hidden;
// Back button toevoegen
Button btnBack = new Button();
grdAdmin.Children.Add(btnBack);
btnBack.Content = "Back";
btnBack.Visibility = Visibility.Visible;
btnBack.Height = 30;
btnBack.Width = 60;
btnBack.Margin = new Thickness(180, 65, 0, 0);
btnBack.VerticalAlignment = VerticalAlignment.Top;
btnBack.HorizontalAlignment = HorizontalAlignment.Left;
//Textboxes & labels toevoegen
//lblUsername
Label lblUsername = new Label();
grdAdmin.Children.Add(lblUsername);
lblUsername.Content = "USERNAME";
lblUsername.Margin = new Thickness(20, 100, 0, 0);
lblUsername.Padding = new Thickness(0, 5, 5, 5);
lblUsername.Height = 30;
lblUsername.Width = 100;
lblUsername.FontSize = 10;
lblUsername.SetValue(Label.FontWeightProperty, FontWeights.Bold);
lblUsername.Opacity = 60;
lblUsername.VerticalAlignment = VerticalAlignment.Top;
lblUsername.HorizontalAlignment = HorizontalAlignment.Left;
//txtUsername
TextBox txtUsername = new TextBox();
grdAdmin.Children.Add(txtUsername);
txtUsername.Text = "";
txtUsername.Margin = new Thickness(20, 130, 0, 0);
txtUsername.Padding = new Thickness(10, 0, 0, 0);
txtUsername.Height = 30;
txtUsername.Width = 220;
txtUsername.VerticalAlignment = VerticalAlignment.Top;
txtUsername.HorizontalAlignment = HorizontalAlignment.Left;
txtUsername.VerticalContentAlignment = VerticalAlignment.Center;
//lblPassword
Label lblPassword = new Label();
grdAdmin.Children.Add(lblPassword);
lblPassword.Content = "PASSWORD";
lblPassword.Margin = new Thickness(20, 160, 0, 0);
lblPassword.Padding = new Thickness(0, 5, 5, 5);
lblPassword.Height = 30;
lblPassword.Width = 100;
lblPassword.FontSize = 10;
lblPassword.SetValue(Label.FontWeightProperty, FontWeights.Bold);
lblPassword.Opacity = 60;
lblPassword.VerticalAlignment = VerticalAlignment.Top;
lblPassword.HorizontalAlignment = HorizontalAlignment.Left;
//pbxPassword
PasswordBox pbxPassword = new PasswordBox();
grdAdmin.Children.Add(pbxPassword);
pbxPassword.Password = "";
pbxPassword.Margin = new Thickness(20, 190, 0, 0);
pbxPassword.Padding = new Thickness(10, 0, 0, 0);
pbxPassword.Height = 30;
pbxPassword.Width = 220;
pbxPassword.VerticalAlignment = VerticalAlignment.Top;
pbxPassword.HorizontalAlignment = HorizontalAlignment.Left;
pbxPassword.VerticalContentAlignment = VerticalAlignment.Center;
pbxPassword.PasswordChar = '*';
//lblRang
Label lblRang = new Label();
grdAdmin.Children.Add(lblRang);
lblRang.Content = "RANG";
lblRang.Margin = new Thickness(20, 220, 0, 0);
lblRang.Padding = new Thickness(0, 5, 5, 5);
lblRang.Height = 30;
lblRang.Width = 100;
lblRang.FontSize = 10;
lblRang.SetValue(Label.FontWeightProperty, FontWeights.Bold);
lblRang.Opacity = 60;
lblRang.VerticalAlignment = VerticalAlignment.Top;
lblRang.HorizontalAlignment = HorizontalAlignment.Left;
//cboRangen
ComboBox cboRangen = new ComboBox();
grdAdmin.Children.Add(cboRangen);
cboRangen.Margin = new Thickness(20, 250, 0, 0);
cboRangen.Height = 30;
cboRangen.Width = 220;
cboRangen.VerticalAlignment = VerticalAlignment.Top;
cboRangen.HorizontalAlignment = HorizontalAlignment.Left;
cboRangen.Items.Add("Directeur");
cboRangen.Items.Add("Software Manager");
//btnRegister
Button btnAddUser = new Button();
grdAdmin.Children.Add(btnAddUser);
btnAddUser.Content = "Add User";
btnAddUser.Visibility = Visibility.Visible;
btnAddUser.Height = 30;
btnAddUser.Width = 220;
btnAddUser.Margin = new Thickness(20, 300, 0, 0);
btnAddUser.VerticalAlignment = VerticalAlignment.Top;
btnAddUser.HorizontalAlignment = HorizontalAlignment.Left;
btnAddUser.Click += BtnAddUser_Click;
}
private void BtnAddUser_Click(object sender, RoutedEventArgs e)
{
MySqlConnection MySqlCon = new MySqlConnection(connectionStr.ConnectionString);
try
{
if (MySqlCon.State == System.Data.ConnectionState.Closed) MySqlCon.Open();
String query2 = "INSERT INTO egh.accounts (Username,Password,Rang) VALUES(#Username, #Password, #Rang)";
MySqlCommand sqlCmd = new MySqlCommand(query2, MySqlCon);
sqlCmd.CommandType = CommandType.Text;
sqlCmd.Parameters.AddWithValue("#Username", txtUsername.Text);
sqlCmd.Parameters.AddWithValue("#Password", pbxPassword.Text);
sqlCmd.Parameters.AddWithValue("#Rang", cboRangen.SelectedValue);
sqlCmd.ExecuteScalar();
MessageBox.Show("User added!");
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
finally
{
MySqlCon.Close();
}
}
}

The variables, that are mentioned, are local to the btnAddUsers_Click() function. They only exist within this function.
To access them, you have several options (including, but not limited to):
Convert the local variables to class members
Find another way to access the component
Add the components at design time and just toggle the visibility.

Related

delegate c# to share data between forms

i have this assignement when i need to create a winform of all classes that i ve implementedalready did form add but got issues in my list form cant access list of borrowers from form add1
here is my form list1.cs
namespace TP.A {
public partial class list1 : Form{
private Button Exit;
private GestionEmprunteur _gestionEmprunteur;
public list1()
{
_gestionEmprunteur = new GestionEmprunteur();
InitializeComponent_D();
InitializeDataGridView();
// Abonnement à l'événement OnAddEmprunteur de l'objet add1
add1 addForm = new add1();
addForm.OnAddEmprunteur += AddEmprunteur;
}
private DataGridView dgvBorrowers;
private void InitializeDataGridView()
{
{
//create DataGridView to display borrowers
dgvBorrowers = new DataGridView();
dgvBorrowers.Location = new Point(100,200);
dgvBorrowers.Size = new Size(798, 450);
dgvBorrowers.AutoGenerateColumns = true;
dgvBorrowers.DataSource = _gestionEmprunteur.Lister2();
this.Controls.Add(dgvBorrowers);
}
}
private void AddEmprunteur(Emprunteur emprunteur)
{
_gestionEmprunteur.AddEmprunteur(emprunteur);
dgvBorrowers.DataSource = _gestionEmprunteur.Lister2();
}
private void InitializeComponent_D()
{
// DESIGN1.ApplyDesign(this);
//create submit button
Exit = new Button();
Exit.Text = "Exit";
Exit.Font = new Font("Times New Roman", 12, FontStyle.Regular);
Exit.Location = new Point((this.Width - Exit.Width) / 2, 500);
Exit.Size = new Size(100, 50);
Exit.Click += new EventHandler(exit_Click);
this.Controls.Add(Exit);
Exit.BringToFront();
Exit.RightToLeft = RightToLeft.Yes;
}
private void exit_Click(object? sender, EventArgs e)
{
this.Close();
} }}
here is my form add1.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Validation.services;
using serie2.Validation.services;
using TP.main;
using System.Windows.Forms;
namespace TP.A
{
public partial class add1 : Form
{
public delegate void AddEmprunteurHandler(Emprunteur emprunteur);
public event AddEmprunteurHandler OnAddEmprunteur;
private Emprunteur emprunteur;
private GestionEmprunteur _gestionEmprunteur;
private TextBox _nameTextBox;
private TextBox _firstNameTextBox;
private Button _submitButton;
private Button _cancelButton;
private Label _nameLabel;
private Label _loginLabel;
private Label _firstNameLabel;
private List<Emprunteur> _emprunteurs;
public add1()
{
_emprunteurs = new List<Emprunteur>();
_gestionEmprunteur = new GestionEmprunteur();
InitializeComponent(this);
}
private void InitializeComponent( Form form)
{
DESIGN1.ApplyDesign(this);
//create label for name
Label loginLabel = new Label();
loginLabel.Text = "Login :";
loginLabel.Left = 0;
loginLabel.ForeColor = Color.White;
loginLabel.BackColor = Color.Black;
loginLabel.BackColor = Color.FromArgb(128, 0, 0, 0);
loginLabel.Location = new Point((form.Width - loginLabel.Width) / 2, 100);
loginLabel.Font = new Font("Andalus", 22, FontStyle.Bold);
loginLabel.AutoSize = true;
// nameLabel.Location = new Point((form.Width - nameLabel.Width) / 2, 250);
this.Controls.Add(loginLabel);
loginLabel.BringToFront();
//create label for name
Label nameLabel = new Label();
nameLabel.Text = "Name:";
nameLabel.Left = 0 ;
nameLabel.ForeColor = Color.White;
nameLabel.BackColor = Color.Black;
nameLabel.BackColor = Color.FromArgb(128, 0, 0, 0);
nameLabel.Location = new Point((form.Width - nameLabel.Width) / 2, 250);
nameLabel.Font = new Font("Times New Roman",16 ,FontStyle.Bold);
nameLabel.AutoSize = true;
// nameLabel.Location = new Point((form.Width - nameLabel.Width) / 2, 250);
this.Controls.Add(nameLabel);
nameLabel.BringToFront();
//create textbox for name
_nameTextBox = new TextBox();
// _nameTextBox.Size = new Size(150, 30);
_nameTextBox.Location = new Point((form.Width - _nameTextBox.Width) / 2, 300);
_nameTextBox.Size = new Size(150, 25);
form.Controls.Add(_nameTextBox);
_nameTextBox.BringToFront();
//create label for first name
Label firstNameLabel = new Label();
firstNameLabel.Text = "First Name:";
firstNameLabel.Left = 0;
firstNameLabel.ForeColor = Color.White;
firstNameLabel.BackColor = Color.Black;
firstNameLabel.BackColor = Color.FromArgb(128, 0, 0, 0);
firstNameLabel.Location = new Point((form.Width - firstNameLabel.Width) / 2, 350);
firstNameLabel.Font = new Font("Times New Roman", 16, FontStyle.Bold);
firstNameLabel.AutoSize = true;
this.Controls.Add(firstNameLabel);
firstNameLabel.BringToFront();
//create textbox for first name
_firstNameTextBox = new TextBox();
_firstNameTextBox.Location = new Point((form.Width - _firstNameTextBox.Width) / 2, 400);
_firstNameTextBox.Size = new Size(150, 25);
form.Controls.Add(_firstNameTextBox);
_firstNameTextBox.BringToFront();
//create submit button
_submitButton = new Button();
_submitButton.Text = "Submit";
_submitButton.Font = new Font("Times New Roman", 12, FontStyle.Regular);
_submitButton.Location = new Point((form.Width - _submitButton.Width) / 2, 500);
_submitButton.Size = new Size(100, 50);
_submitButton.Click += new EventHandler(SubmitButton_Click);
form.Controls.Add(_submitButton);
_submitButton.BringToFront();
_submitButton.RightToLeft= RightToLeft.Yes;
//create cancel button
_cancelButton = new Button();
_cancelButton.Text = "Cancel";
_cancelButton.Font = new Font("Times New Roman", 12, FontStyle.Regular);
_cancelButton.Location = new Point((form.Width - _submitButton.Width) / 180, 500);
_cancelButton.Size = new Size(100, 50);
_cancelButton.Click += new EventHandler(cancel_Click);
form.Controls.Add(_cancelButton);
_cancelButton.BringToFront();
}
private void cancel_Click(object? sender, EventArgs e)
{
this.Close();
}
private void SubmitButton_Click(object sender, EventArgs e)
{
if (!string.IsNullOrWhiteSpace(_nameTextBox.Text) && !string.IsNullOrWhiteSpace(_firstNameTextBox.Text))
{
Emprunteur emp = new Emprunteur { Nom = _nameTextBox.Text, Prenom = _firstNameTextBox.Text };
bool success = _gestionEmprunteur.AddEmprunteur(emp);
// Appel de l'événement OnAddEmprunteur
OnAddEmprunteur?.Invoke(emp);
if (success)
{
MessageBox.Show("Borrower added successfully.", "Success", MessageBoxButtons.OK, MessageBoxIcon.Information);
_nameTextBox.Text = "";
_firstNameTextBox.Text = "";
}
else
{
MessageBox.Show("An error occurred while adding the borrower.", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
_gestionEmprunteur.Lister();
}
else
{
MessageBox.Show("Please enter a name and first name for the borrower.", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
}
}
HERE ARE THE MODICATION THAT I UNCLUDED i want to share data of datagrid from my form add1.cs to my form list1.cs i added a datagrid in my form1 to ensure that my data are displayed correctly
but m facing issues to connect both forms
public partial class add1 : Form
{
private Emprunteur emprunteur;
static GestionEmprunteur _gestionEmprunteur;
private TextBox _nameTextBox;
private TextBox _firstNameTextBox;
private Button _submitButton;
private Button _cancelButton;
private Label _nameLabel;
private Label _loginLabel;
private Label _firstNameLabel;
static List<Emprunteur> _emprunteurs;
private DataGridView dgvBorrowers;
public add1()
{
dgvBorrowers = new DataGridView();
dgvBorrowers.Location = new Point(40, 190);
dgvBorrowers.Size = new Size(450, 300);
dgvBorrowers.AutoGenerateColumns = true;
this.Controls.Add(dgvBorrowers);
_emprunteurs = new List<Emprunteur>();
_gestionEmprunteur = new GestionEmprunteur();
InitializeComponent(this);
}
private void InitializeComponent(Form form)
{
DESIGN1.ApplyDesign(this);
//create label for name
Label loginLabel = new Label();
loginLabel.Text = "Login :";
loginLabel.Left = 0;
loginLabel.ForeColor = Color.White;
loginLabel.BackColor = Color.Black;
loginLabel.BackColor = Color.FromArgb(128, 0, 0, 0);
loginLabel.Location = new Point((form.Width - loginLabel.Width) / 2, 100);
loginLabel.Font = new Font("Andalus", 22, FontStyle.Bold);
loginLabel.AutoSize = true;
// nameLabel.Location = new Point((form.Width - nameLabel.Width) / 2, 250);
this.Controls.Add(loginLabel);
loginLabel.BringToFront();
//create label for name
Label nameLabel = new Label();
nameLabel.Text = "Name:";
nameLabel.Left = 0;
nameLabel.ForeColor = Color.White;
nameLabel.BackColor = Color.Black;
nameLabel.BackColor = Color.FromArgb(128, 0, 0, 0);
nameLabel.Location = new Point((form.Width - nameLabel.Width) / 2, 250);
nameLabel.Font = new Font("Times New Roman", 16, FontStyle.Bold);
nameLabel.AutoSize = true;
// nameLabel.Location = new Point((form.Width - nameLabel.Width) / 2, 250);
this.Controls.Add(nameLabel);
nameLabel.BringToFront();
//create textbox for name
_nameTextBox = new TextBox();
// _nameTextBox.Size = new Size(150, 30);
_nameTextBox.Location = new Point((form.Width - _nameTextBox.Width) / 2, 300);
_nameTextBox.Size = new Size(150, 25);
form.Controls.Add(_nameTextBox);
_nameTextBox.BringToFront();
//create label for first name
Label firstNameLabel = new Label();
firstNameLabel.Text = "First Name:";
firstNameLabel.Left = 0;
firstNameLabel.ForeColor = Color.White;
firstNameLabel.BackColor = Color.Black;
firstNameLabel.BackColor = Color.FromArgb(128, 0, 0, 0);
firstNameLabel.Location = new Point((form.Width - firstNameLabel.Width) / 2, 350);
firstNameLabel.Font = new Font("Times New Roman", 16, FontStyle.Bold);
firstNameLabel.AutoSize = true;
this.Controls.Add(firstNameLabel);
firstNameLabel.BringToFront();
//create textbox for first name
_firstNameTextBox = new TextBox();
_firstNameTextBox.Location = new Point((form.Width - _firstNameTextBox.Width) / 2, 400);
_firstNameTextBox.Size = new Size(150, 25);
form.Controls.Add(_firstNameTextBox);
_firstNameTextBox.BringToFront();
//create submit button
_submitButton = new Button();
_submitButton.Text = "Submit";
_submitButton.Font = new Font("Times New Roman", 12, FontStyle.Regular);
_submitButton.Location = new Point((form.Width - _submitButton.Width) / 2, 500);
_submitButton.Size = new Size(100, 50);
_submitButton.Click += new EventHandler(SubmitButton_Click);
form.Controls.Add(_submitButton);
_submitButton.BringToFront();
_submitButton.RightToLeft = RightToLeft.Yes;
//create cancel button
_cancelButton = new Button();
_cancelButton.Text = "Cancel";
_cancelButton.Font = new Font("Times New Roman", 12, FontStyle.Regular);
_cancelButton.Location = new Point((form.Width - _submitButton.Width) / 180, 500);
_cancelButton.Size = new Size(100, 50);
_cancelButton.Click += new EventHandler(cancel_Click);
form.Controls.Add(_cancelButton);
_cancelButton.BringToFront();
}
private void cancel_Click(object? sender, EventArgs e)
{
this.Close();
}
private void SubmitButton_Click(object sender, EventArgs e)
{
if (!string.IsNullOrWhiteSpace(_nameTextBox.Text) && !string.IsNullOrWhiteSpace(_firstNameTextBox.Text))
{
Emprunteur emp = new Emprunteur(_nameTextBox.Text, _firstNameTextBox.Text);
bool success = _gestionEmprunteur.AddEmprunteur(emp);
if (success)
{
MessageBox.Show("Borrower added successfully.", "Success", MessageBoxButtons.OK, MessageBoxIcon.Information);
dgvBorrowers.DataSource = _gestionEmprunteur._emprunteurs;
_nameTextBox.Text = "";
_firstNameTextBox.Text = "";
}
else
{
MessageBox.Show("An error occurred while adding the borrower.", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
else
{
MessageBox.Show("Please enter a name and first name for the borrower.", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
public list1()
{
_gestionEmprunteur = new GestionEmprunteur();
InitializeComponent_D();
InitializeDataGridView();
}
private void InitializeDataGridView()
{
dgvBorrowers = new DataGridView();
dgvBorrowers.Location = new Point(100, 200);
dgvBorrowers.Size = new Size(798, 450);
dgvBorrowers.AutoGenerateColumns = true;
dgvBorrowers.DataSource = _gestionEmprunteur._emprunteurs;
this.Controls.Add(dgvBorrowers);
}

Show blank date range on winforms but populate upon selecting date

I've got the first part working which is I want a date selection box to pop up with initial blanks in the date box. After selecting the dates I want them to be populated in the blank spaces. So far when I select the dates it still remains blanks
what I've tried so far is below; To be more specific the button click is where I'm expecting the date range to reappear.
DateTime dtpStartDate = new DateTime(1000, 1, 1);
DateTime dtpEndDate = new DateTime(1000, 1, 1);
Form frm = new Form();
frm.StartPosition = FormStartPosition.CenterScreen;
frm.Height = 160;
frm.Width = 300;
Label lbl = new Label();
lbl.Text = "Select Date Range";
lbl.AutoSize = true;
lbl.Width = 165;
lbl.Height = 13;
lbl.Font = new Font(FontFamily.GenericSansSerif, 8.25F, FontStyle.Bold);
lbl.Location = new Point(66, 10);
Label lblStartDate = new Label();
lblStartDate.Text = "Start Month/Year:";
lblStartDate.AutoSize = true;
lblStartDate.Location = new Point(13, 26);
Label lblEndDate = new Label();
lblEndDate.Text = "End Month/Year:";
lblEndDate.AutoSize = true;
lblEndDate.Location = new Point(165, 26);
DateTimePicker dtpStart = new DateTimePicker();
dtpStart.Location = new Point(12, 45);
dtpStart.Format = DateTimePickerFormat.Custom;
dtpStart.CustomFormat = " ";
dtpStart.Width = 120;
dtpStart.Value = first;
DateTimePicker dtpEnd = new DateTimePicker();
dtpEnd.Location = new Point(165, 45);
dtpEnd.Format = DateTimePickerFormat.Custom;
dtpEnd.CustomFormat = " ";
dtpEnd.Width = 120;
dtpEnd.Value = last;
Button btn = new Button();
btn.Text = "Submit";
btn.Location = new Point(100, 80);
btn.Click += (object sender, EventArgs e) =>
{
dtpStart.Enabled = true;
dtpStart.CustomFormat = "MMMM yyyy";
dtpEnd.Enabled = true;
dtpEnd.CustomFormat = "MMMM yyyy";
dtpStartDate = dtpStart.Value;
dtpEndDate = dtpEnd.Value;
frm.Close();
};
frm.Controls.Add(lbl);
frm.Controls.Add(lblStartDate);
frm.Controls.Add(lblEndDate);
frm.Controls.Add(dtpStart);
frm.Controls.Add(dtpEnd);
frm.Controls.Add(btn);
frm.Controls.Add(checkBoxBlanks11);
frm.ShowDialog();
I changed the format in the ValueChanged event and it worked. I took your code as it was, added the new handler. That's it.
{
...
dtpStart.ValueChanged += DtpStartValueChanged;
...
}
private void DtpStartValueChanged(object? sender, EventArgs e)
{
var dtpStart = (DateTimePicker)sender;
dtpStart.Format = DateTimePickerFormat.Short;
}
You are expecting to appear the dates on the button click, but you close the frm form in your button click handler.

Controls.Find not working within specific if-statement?

I´m stuck on a problem using controls.find and I can´t find the error.
I´m creating a loginform using different panels.
Panels are created as follows:
public Panel CreatePanel()
{
Panel login = new Panel();
TextBox Login_UsernameTB = new TextBox();
TextBox Login_PasswordTB = new TextBox();
Label label1 = new Label();
Label label2 = new Label();
Label loginstatus = new Label();
Button Login_Loginbtn = new Button();
Button Login_Registerbtn = new Button();
PictureBox Login_Logo = new PictureBox();
PictureBox Login_ECard = new PictureBox();
//creatingPanel
login.Location = new Point(0, 0);
login.Name = "Login";
login.Size = new Size(1000, 400);
//locations
Login_ECard.Location = new Point(500, 250);
Login_ECard.SizeMode = PictureBoxSizeMode.StretchImage;
Login_ECard.Image = PatientSimulator.Properties.Resources.Ecard;
Login_ECard.Name = "Login_Ecard";
Login_Logo.Location = new Point(148, 12);
Login_Logo.SizeMode = PictureBoxSizeMode.StretchImage;
Login_Logo.Image = PatientSimulator.Properties.Resources.Logo;
Login_Logo.Name = "Login_Logo";
label1.Location = new Point(31, 200);
label1.Size = new Size(58, 13);
label1.Text = "Username:";
label1.Name = "label1";
label2.Location = new Point(31, 244);
label2.Size = new Size(56, 13);
label2.Text = "Password:";
label2.Name = "label2";
Login_UsernameTB.Location = new Point(148, 197);
Login_UsernameTB.Size = new Size(359, 20);
Login_UsernameTB.Text = "Testfirma1";
Login_UsernameTB.Name = "Login_UsernameTB";
Login_PasswordTB.Location = new Point(148, 241);
Login_PasswordTB.Size = new Size(359, 20);
Login_PasswordTB.Text = "Hallo1234#";
Login_PasswordTB.PasswordChar = '*';
Login_PasswordTB.Name = "Login_PasswordTB";
Login_Loginbtn.Location = new Point(432, 334);
Login_Loginbtn.Size = new Size(75, 23);
Login_Loginbtn.Text = "Login";
Login_Loginbtn.Click += Login_Loginbtn_Click;
loginstatus.Location = new Point(323, 360);
loginstatus.Size = new Size(300, 20);
loginstatus.Text = "";
loginstatus.Name = "loginstatus";
Login_Registerbtn.Location = new Point(323, 334);
Login_Registerbtn.Size = new Size(75, 23);
Login_Registerbtn.Text = "Register";
Login_Registerbtn.Click += Login_Registerbtn_Click;
login.Controls.Add(Login_ECard);
login.Controls.Add(Login_Logo);
login.Controls.Add(label1);
login.Controls.Add(label2);
login.Controls.Add(Login_UsernameTB);
login.Controls.Add(Login_PasswordTB);
login.Controls.Add(Login_Loginbtn);
login.Controls.Add(Login_Registerbtn);
login.Controls.Add(loginstatus);
return login;
}
In Form_load:
Panel login = CreatePanel();
login.Visible = true;
Controls.Add(login);
When I start the application, everything is displayed. if I type some text into systemstatus.text isn't gets displayed.
When doing a check if the entered password & username are correct, the strange stuff happens.
private void Login_Loginbtn_Click(object sender, EventArgs e)
{
Patient.DBAccess db = new Patient.DBAccess();
Sha256 sha = new Sha256();
string username = login.Controls.Find("Login_UsernameTB", true)[0].Text;
string userpw = login.Controls.Find("Login_PasswordTB", true)[0].Text;
Patient.DatabaseRequestInterface.UserInterface user = new Patient.DatabaseRequestInterface.UserInterface();
user.Username = username;
if (db.IsUserExisting(user)){
user = db.ReadUserPassword(user);
string salt = Encoding.ASCII.GetString(user.PasswordSalt);
byte[] pw = sha.GetSha256(userpw, salt);
if (pw.SequenceEqual(user.PasswordHash))
{
//Programm starten
//token generieren
Patient.DatabaseRequestInterface.UserInterface useri = db.ReadFullUser(user);
UserAuthentificationToken = new UserInfo(useri.Username, useri.Uuid, DateTime.Now);
LoginSuccessEvent?.Invoke(this, new EventArgs());
login.Controls.Find("loginstatus", true)[0].Text = "Login successfull";
this.Close();
}
else
{
MessageBox.Show("Login failed, Username and/or password incorrect");
}
}
else
{
MessageBox.Show("Falscher User oder Passwort");
//Controls.Find("Login_StatusL", true)[0].Text = "Login failed, Username and/or password incorrect!";
}
}
The first 2 times I use controls.find it works, I get the strings entered by the users at the corresponding TextBoxes. When I try to change loginstatus, I get a System.IndexOutOfRangeException. My interpretation of the exception is, that there was no loginstatus found. And I don´t understand why. (the other 2 elements can´t be found within the if as well)
Can anyone help?
the controls.find("string",true)[0].Text = "XXX" works, I use it a lot at another part of the application
Any ideas?
Thanks in advance,
David
You miss the Name property in your code and Controls.Find strictly work on Name
Login_UsernameTB.Name = "Login_UsernameTB";
So your Code should be something like this:
public Panel CreatePanel()
{
Panel login = new Panel();
login.Size = new Size(900, 900);
TextBox Login_UsernameTB = new TextBox();
Login_UsernameTB.Name = "Login_UsernameTB";
Login_UsernameTB.Location = new Point(50, 50);
Login_UsernameTB.Text = "Username here";
TextBox Login_PasswordTB = new TextBox();
Login_PasswordTB.Name = "Login_PasswordTB";
Login_PasswordTB.Location = new Point(150, 50);
Login_PasswordTB.Text = "password here";
//stuff is asigned to TBs...
Label loginstatus = new Label();
loginstatus.Location = new Point(150, 150);
loginstatus.Size = new Size(300, 20);
loginstatus.Text = "";
loginstatus.Name = "loginstatus";
login.Controls.Add(Login_UsernameTB);
login.Controls.Add(Login_PasswordTB);
login.Controls.Add(loginstatus);
return login;
}
Also, the login should be class level but not defined inside the Form_Load
like this :
public partial class Form1 : Form
{
Panel login;
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
login = CreatePanel();
login.Visible = true;
Controls.Add(login);
}
.....
I have tested it and works fine.
My test code is
using System;
using System.Drawing;
using System.Windows.Forms;
namespace SackOverflow
{
public partial class Form1 : Form
{
Panel login;
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
login = CreatePanel();
login.Visible = true;
Controls.Add(login);
}
public Panel CreatePanel()
{
Panel login = new Panel();
login.Size = new Size(900, 900);
TextBox Login_UsernameTB = new TextBox();
Login_UsernameTB.Name = "Login_UsernameTB";
Login_UsernameTB.Location = new Point(50, 50);
Login_UsernameTB.Text = "Username";
TextBox Login_PasswordTB = new TextBox();
Login_PasswordTB.Name = "Login_PasswordTB";
Login_PasswordTB.Location = new Point(150, 50);
Login_PasswordTB.Text = "password";
//stuff is asigned to TBs...
Label loginstatus = new Label();
loginstatus.Location = new Point(150, 150);
loginstatus.Size = new Size(300, 20);
loginstatus.Text = "";
loginstatus.Name = "loginstatus";
login.Controls.Add(Login_UsernameTB);
login.Controls.Add(Login_PasswordTB);
login.Controls.Add(loginstatus);
return login;
}
private void button1_Click(object sender, EventArgs e)
{
if (true)
{
string username = login.Controls.Find("Login_UsernameTB", true)[0].Text;
string userpw = login.Controls.Find("Login_PasswordTB", true)[0].Text;
//UserInterface user = //some database stuff to get the password saved by the user
if ("123" == userpw)
{
login.Controls.Find("loginstatus", true)[0].Text = "Logging in";
Login();
}
else
{
login.Controls.Find("loginstatus", true)[0].Text = "Error";
}
}
}
private void Login()
{
MessageBox.Show("Login");
}
}
}
Result is:
I receive the message box MessageBox.Show("Login"); shown and Loginstatus is shown too.

How to fit picture and text inside a flowlayoutpanel with a dynamically created radiobutton in c#

I have a program that displays a candidate running in a position. Example President. I made a all my controls dynamic. I created a FlowLayoutPanel and inside is a RadioButton which has a .Text of the candidate.
My code :
private void FPreview_Load(object sender, EventArgs e)
{
PanelPresident();
}
FlowLayoutPanel PresPanel = new FlowLayoutPanel();
private void PanelPresident()
{
Label PresLabel = new Label();
PresLabel.Text = "PRESIDENT";
PresLabel.AutoSize = true;
PresLabel.Location = new Point(50, 210);
PresLabel.Font = new Font(this.Font, FontStyle.Bold);
PresLabel.Font = new Font("Courier New", 15);
PresLabel.ForeColor = Color.Aquamarine;
this.Controls.Add(PresLabel);
PresPanel.Size = new Size(160, 300);
PresPanel.Location = new Point(30, 240);
PresPanel.FlowDirection = FlowDirection.TopDown;
PresPanel.BorderStyle = BorderStyle.FixedSingle;
PresPanel.AutoScroll = true;
PresPanel.BackColor = Color.Maroon;
PresPanel.WrapContents = false;
Controls.Add(PresPanel);
PresPanel.SuspendLayout();
try
{
string cmdPres = "SELECT (LastName + ', ' + FirstName + ' ' + MiddleName) as PresName, " +
"imgPath as PresImagePath, " + "id as PresID FROM TableVote WHERE Position='President'";
using (SqlCommand Prescom = new SqlCommand(cmdPres, sc))
{
if (sc.State != ConnectionState.Open) sc.Open();
SqlDataReader Presreader = Prescom.ExecuteReader();
while (Presreader.Read())
{
PresRadioButton(Presreader.GetString(0), Presreader.GetString(1), Presreader.GetInt32(2));
}
Presreader.Close();
sc.Close();
PresPanel.ResumeLayout(true);
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
public void PresRadioButton(string PresName, string PresimagePath, int PresID)
{
RadioButton Presradio = new RadioButton { Text = PresName, Parent = PresPanel };
Presradio.AutoSize = false;
Presradio.Size = new Size(130, 130);
Presradio.Image = new Bitmap(Image.FromFile(PresimagePath), 90, 90);
Presradio.TextImageRelation = TextImageRelation.ImageAboveText;
Presradio.CheckAlign = ContentAlignment.BottomCenter;
Presradio.ImageAlign = ContentAlignment.MiddleCenter;
Presradio.TextAlign = ContentAlignment.MiddleCenter;
Presradio.ForeColor = Color.LimeGreen;
Presradio.Tag = PresID;
}
My Problem is, if the Text of radiobutton is long, the picture wont fit. it does not show the full picture. Can you help me fix this problem by fitting my picture inside the flowlayoutpanel even though the text is long. Thanks :)

How do I use the save feature on tabcontols?

I have a form where I can add tabs into a tabcontrol by pressing a button on the form. There are 4 textboxes and then the name of the tab. I have added using system.io;
Where would I even start to create a save for all of the tabs? I have the save button created, I just don't know where to start. I would guess I would need a loop of some kind.
namespace WindowsFormsApplication4
{
public partial class Form1 : Form
{
public string status = "no";
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
string name = txtName.Text;
//validate information
try { }
catch { }
//create new tab
string title = name;
TabPage myTabPage = new TabPage(title);
tabControl1.TabPages.Add(myTabPage);
//Add Labels
Label lb = new Label();
lb.Text = "Denomination:";
lb.Location = new System.Drawing.Point(150, 75);
lb.Name = "lbl";
lb.Size = new System.Drawing.Size(100, 20);
myTabPage.Controls.Add(lb);
Label lb2 = new Label();
lb2.Text = "Year:";
lb2.Location = new System.Drawing.Point(150, 120);
lb2.Name = "lbl2";
lb2.Size = new System.Drawing.Size(100, 20);
myTabPage.Controls.Add(lb2);
Label lb3 = new Label();
lb3.Text = "Grade:";
lb3.Location = new System.Drawing.Point(150, 165);
lb3.Name = "lbl3";
lb3.Size = new System.Drawing.Size(100, 20);
myTabPage.Controls.Add(lb3);
Label lb4 = new Label();
lb4.Text = "Mint Mark:";
lb4.Location = new System.Drawing.Point(150, 210);
lb4.Name = "lbl4";
lb4.Size = new System.Drawing.Size(100, 20);
myTabPage.Controls.Add(lb4);
//Add text boxes
TextBox tb = new TextBox();
tb.Location = new System.Drawing.Point(250, 75);
tb.Name = "txt";
tb.Size = new System.Drawing.Size(184, 20);
myTabPage.Controls.Add(tb);
TextBox tb1 = new TextBox();
tb1.Location = new System.Drawing.Point(250, 120);
tb1.Name = "txt1";
tb1.Size = new System.Drawing.Size(184, 20);
myTabPage.Controls.Add(tb1);
TextBox tb2 = new TextBox();
tb2.Location = new System.Drawing.Point(250, 165);
tb2.Name = "txt2";
tb2.Size = new System.Drawing.Size(184, 20);
myTabPage.Controls.Add(tb2);
TextBox tb3 = new TextBox();
tb3.Location = new System.Drawing.Point(250, 210);
tb3.Name = "txt3";
tb3.Size = new System.Drawing.Size(184, 20);
myTabPage.Controls.Add(tb3);
//put data inside of textboxes
tb.Text = txtCoin.Text;
tb1.Text = txtYear.Text;
tb2.Text = txtGrade.Text;
tb3.Text = txtMint.Text;
// Add delete button
Button bn = new Button();
bn.Location = new System.Drawing.Point(560, 350);
bn.Name = "btnDelete";
bn.Text = "Delete";
bn.Size = new System.Drawing.Size(100, 50);
bn.Click += MyClick;
myTabPage.Controls.Add(bn);
}
private void MyClick(object sender, EventArgs e)
{
Form2 myform = new Form2();
myform.ShowDialog();
if (status == "yes")
{ tabControl1.TabPages.Remove(tabControl1.SelectedTab); }
status = "no";
}
private void btnExit_Click(object sender, EventArgs e)
{
this.Close();
}
private void Form1_FormClosing(object sender, FormClosingEventArgs e)
{
int counter;
int ccounter;
string outLine;
string pathFileName = Path.Combine(Application.StartupPath, "coins.dat");
StreamWriter writeIt = new StreamWriter(pathFileName);
for (counter = 0; ((tabControl1.TabCount) -1) != 0 ;)
{
}
writeIt.Close();
}
}
}
Use a foreach loop instead of your for (counter = 0; ((tabControl1.TabCount) -1) != 0 ;) loop:
foreach (TabPage tabPage in tabControl.TabPages)
Your for loop is a infinite loop, do it like that:
for (counter = 0; counter < tabControl1.TabCount; counter++)
{
// Save the tab
}

Categories

Resources