I have an user control calling a method on my main form and this method should enable a button (by default this button is disabled) on the same form, but it's not working.
private void button1_Click(object sender, EventArgs e)
{
Form1 fr = new Form1();
fr.login(textBox1.Text, textBox2.Text);
}
And here is my method
public void login(string username, string password)
{
Connect();
sendMessage("LoginAction,Username=" + username + "UserPassword=" + password);
}
Here is where the button is enabled
private void commandInterpreter(string Message)
{
if(Message.Contains("LoginSuccess,") == true)
{
name = Message.Remove(Message.IndexOf("LoginSuccess,Name="), 18);
Bt2En = true;
}
}
Here is where I'm exposing my button properties:
public bool Bt2En
{
get { return button2.Enabled; }
set { button2.Enabled = value; }
}
I solved my problem doing this, these are my methods from Form1:
public void login()
{
Connect();
Login lg = this.lg;
string username = lg.Username;
string password = lg.Password;
MessageBox.Show(username + "\n" + password);
}
private void button1_Click(object sender, EventArgs e)
{
login();
}
And this one is from my user control:
public string Username
{
get { return textBox1.Text; }
}
public string Password
{
get { return textBox2.Text; }
}
Thanks Steve and Bradley Uffner for help and everyone who tried. I'm posting the answer for who has the same problem.
Bt2En is a property but You use such as methods.
public void bt2En(bool flag)
{
if(flag)
button.Enable=true;
}
Related
I have 2 forms: Game and newPlayer. When you press a button in Game, it opens the dialog of the newPlayer form, where someone would type his/her name and choose a Color in a comboBox between red, green, blue or yellow. I save that information in 2 variables: name (string) and color (int - being the index of the comboBox). I want to pass those 2 variables to the form Game.
I've tried unifying them in just one string and pass just one variabe to Game form, without success.
public partial class Game : Form
{
static int nPlayers = 4;
static List<Player> players = new List<Player>();
public string name = "";
private void button3_Click(object sender, EventArgs e)
{
using (newPlayer np = new newPlayer())
{
if (np.ShowDialog() == DialogResult.OK)
{
this.name = np.TheValue;
}
}
MessageBox.Show("Welcome " + name + "!");
}
and then:
public partial class newPlayer : Form
{
public string name = "";
public string TheValue
{
get { return this.name; }
}
private void button1_Click(object sender, EventArgs e)
{
if (textBox1.Text != "")
{
if (comboBox1.SelectedIndex > -1)
{
this.name = textBox1.Text + comboBox1.SelectedIndex.ToString();
MessageBox.Show(newPlayer.name);
this.Close();
} else
{
MessageBox.Show("Write your name and choose a color!");
}
} else
{
MessageBox.Show("Write your name and choose a color!");
}
}
On the MessageBox of newPlayer it appears correctly like "Name1", for example. But on the MessageBox of Game, it appears empty. Can someone help, please?
You have forgotten to set the DialogResult when closing the form.
Try this:
this.DialogResult = DialogResult.OK;
this.Close();
If I were writing this code I might have done it more like this:
Game:
public partial class Game : Form
{
public Game()
{
InitializeComponent();
}
private string _playerName = "";
private void button3_Click(object sender, EventArgs e)
{
using (NewPlayer np = new NewPlayer())
{
if (np.ShowDialog() == DialogResult.OK)
{
_playerName = np.PlayerName;
MessageBox.Show($"Welcome {_playerName}!");
}
}
}
}
NewPlayer:
public partial class NewPlayer : Form
{
public NewPlayer()
{
InitializeComponent();
}
private string _playerName = "";
public string PlayerName
{
get { return _playerName; }
}
private void button1_Click(object sender, EventArgs e)
{
if (textBox1.Text != "" && comboBox1.SelectedIndex > -1)
{
_playerName = $"{textBox1.Text}{comboBox1.SelectedIndex}";
MessageBox.Show(_playerName);
this.DialogResult = DialogResult.OK;
this.Close();
}
else
{
MessageBox.Show("Write your name and choose a color!");
}
}
}
So my program is a simple form that a user has to read, agree to the terms, and close the window. When the user closes the window it takes their login name and date / time, writes it to a txt file and exits. When the program loads, I want it to check the file for the existing username. If it finds the username, check the date on which it was recorded and if it was within 6 months exit the program. If it was recorded more than 6 months ago, run the program. Obviously, if the reading of the file doesn't find the username I want the program to run as well. Here is my code so far -
namespace EUSAA
{
public partial class frmMain : Form
{
public frmMain()
{
InitializeComponent();
txtDateTime.Text = DateTime.Now.ToString();
txtUsername.Text = System.Security.Principal.WindowsIdentity.GetCurrent().Name;
btnClose.Visible = false;
chkAgree.Visible = true;
rtbSecurityAwareness.LoadFile("Security Awareness.rtf");
}
private void chkAgree_CheckedChanged(object sender, EventArgs e)
{
if (chkAgree.Checked)
{
btnClose.Visible = true;
}
else btnClose.Visible = false;
}
private void btnClose_Click(object sender, EventArgs e)
{
using (StreamWriter sw = File.AppendText(#"I:\Security Awareness Signed Users\Signed Users.txt"))
{
sw.WriteLine(System.Security.Principal.WindowsIdentity.GetCurrent().Name + "\t" + DateTime.Now.ToString());
}
Environment.Exit(0);
}
This isn't a code writing site; but I was feeling generous. The following class encapsulates storing and retrieving the latest agreement for the current user.
public class AgreementRepository
{
private const string FileLocation = #"I:\Security Awareness Signed Users\Signed Users.txt";
private const char Separator = '\t';
public void AppendAgreementForCurrentUser()
{
string currentUser = GetCurrentUser();
using (StreamWriter sw = File.AppendText(FileLocation))
{
sw.WriteLine($"{currentUser}{Separator}{DateTime.Now:O}");
}
}
public DateTime? GetLastAgreementForCurrentUser()
{
string currentUser = GetCurrentUser();
if (File.Exists(FileLocation) == false)
{
return null;
}
var lastAgreement = File.ReadLines(FileLocation)
.Select(x => x.Split(Separator))
.Where(x => x.Length == 2 && string.Equals(x[0], currentUser, StringComparison.CurrentCultureIgnoreCase))
.Select(x => GetDateTime(x[1]))
.Max();
return lastAgreement;
}
private static DateTime? GetDateTime(string input)
{
DateTime result;
if (DateTime.TryParse(input, out result))
{
return result;
}
return null;
}
private static string GetCurrentUser()
{
return System.Security.Principal.WindowsIdentity.GetCurrent().Name;
}
}
To use this, your form would become...
public partial class frmMain : Form
{
private readonly AgreementRepository _agreementRepository;
public frmMain()
{
_agreementRepository = new AgreementRepository();
InitializeComponent();
txtDateTime.Text = DateTime.Now.ToString();
txtUsername.Text = System.Security.Principal.WindowsIdentity.GetCurrent().Name;
btnClose.Visible = false;
chkAgree.Visible = true;
rtbSecurityAwareness.LoadFile("Security Awareness.rtf");
this.Load += Form1_Load;
}
private void Form1_Load(object sender, EventArgs e)
{
var lastAgreement = _agreementRepository.GetLastAgreementForCurrentUser();
// NOTE: The following condition deals with the fact that lastAgreement could be null
if (lastAgreement > DateTime.Now.AddMonths(-6))
{
Close(); // or Environment.Exit; depends what you need
}
}
private void chkAgree_CheckedChanged(object sender, EventArgs e)
{
btnClose.Visible = chkAgree.Checked; // simplification of your posted code
}
private void btnClose_Click(object sender, EventArgs e)
{
_agreementRepository.AppendAgreementForCurrentUser();
Environment.Exit(0); // Would 'Close()' be enough?
}
Hope this helps
This question already has an answer here:
How to open new form, pass parameter and return parameter back
(1 answer)
Closed 4 years ago.
frmPlaceOrder is my form1. I need to pass the firstName, lastname and Address from this form to the second one which will do the other functions. I don't know how to do that.
namespace Lab1_OrderCake
{
public partial class frmPlaceOrder : Form
{
public static CustomerInformation customer;
public static Address address;
public frmPlaceOrder()
{
InitializeComponent();
customer = new CustomerInformation(txtFName.Text, txtLName.Text);
address = new Address(txtAddress.Text, txtCity.Text, txtPC.Text, txtProvince.Text);
}
private void btnPlaceOrder_Click(object sender, EventArgs e)
{
DialogResult dlgMsg;
if (txtFName.Text == "")
{
MessageBox.Show("Please enter first name", "Data Missing");
txtFName.Focus();
return;
}
if (txtLName.Text == "")
{
MessageBox.Show("Please enter Last name", "Data Missing");
txtLName.Focus();
return;
}
else
{
frmCakeOrder newCust = new frmCakeOrder();
this.Hide();
newCust.ShowDialog();
this.Close();
}
}
}
}
The second form; after the first one has been filled out needs to take the values from form1 and display it with the other values(frmCakeOrder values) in the second form. It needs to be seen in the View and Order events when i click it.
here is the Second form:
namespace Lab1_OrderCake
{
public partial class frmCakeOrder : Form
{
Order cakeOrder;
public List<Cake> cakeList;
public frmCakeOrder()
{
InitializeComponent();
cmbTraditionalCake.SelectedIndex = 0;
cakeOrder = new Order();
gbCustomCake.Visible = false;
this.Size = new Size(700,360);
cakeList = new List<Cake>();
}
private void bttnOrder_Click(object sender, EventArgs e)
{
DialogResult dlgMsg;
dlgMsg = MessageBox.Show(cakeOrder.ToString(), "Confirm Order", MessageBoxButtons.YesNo, MessageBoxIcon.Information);
if (dlgMsg == DialogResult.Yes)
{
MessageBox.Show(cakeOrder.PrintConfirmation());
}
else
{
MessageBox.Show ("The order has not been placed");
}
bttnReset.Focus();
cakeOrder.ClearCart();
}
private void radCustom_CheckedChanged(object sender, EventArgs e)
{
if (radCustom.Checked)
{
cmbTraditionalCake.Enabled = false;
gbCustomCake.Visible = true;
}
else
{
cmbTraditionalCake.Enabled = true;
gbCustomCake.Visible = false;
}
}
private void btnView_Click(object sender, EventArgs e)
{
DialogResult dlgMsg;
cakeOrder.NumOfCakes=1;
dlgMsg = MessageBox.Show(cakeOrder.ToString(), "Your order: ", MessageBoxButtons.YesNo , MessageBoxIcon.Information);
if (dlgMsg == DialogResult.No)
{
cakeOrder.ClearCart();
MessageBox.Show("Please enter and confirm your order!");
}
private void btnAdd_Click(object sender, EventArgs e)
{
if (radCustom.Checked)
{
string flavour, occasion;
flavour = occasion = "";
int layers;
//for flavor
if (radBanana.Checked)
flavour = "Banana";
else if (radChocolate.Checked)
flavour = "Chocolate";
else if (radVanilla.Checked)
flavour = "Vanilla";
if (radTier2.Checked)
layers = 2;
else if (radTier3.Checked)
layers = 3;
else
layers = 1;
if (radGraduation.Checked)
occasion = radGraduation.Text.TrimStart(new char[] { '&' });
else if (radWedding.Checked)
occasion = radWedding.Text.TrimStart(new char[] { '&' });
else occasion = radAnniversary.Text.TrimStart(new char[] { '&' });
cakeOrder.AddCake(new Custom(flavour, occasion, layers));
}
else
{
cakeOrder.AddCake(new Traditional(cmbTraditionalCake.SelectedItem.ToString()));
}
cakeList.Add(cakeOrder);
}
}
}
There are many ways to do this. Try it this way.
private void btnPlaceOrder_Click(object sender, EventArgs e) {
string fname = textBox1.Text;
frmCakeOrder frm = new frmCakeOrder(textBox1.Text);
frm.Show();
}
And in frmCakeOrder,
public frmCakeOrder(string fname) {
InitializeComponent();
textBox1.Text = fname;
}
You can pass the data in the constructor:
public class Form1: from{
//constructor
public void Form1(){
}
public void button_click(){
//Get the data
var firstName = textFirstName.text;
var secondName= textSecondName.text;
var address= textAddress.text;
//Pass the data on the constructor of Form2
Form2 f2 = new Form2(firstName,secondName, address);
f2.show();
}
}
public class Form2: Form{
//constructor with data or parameters
public void Form2(string firstName, string lastName, string Address){
//do dosomething with the data
txtFirstName.text = firstName;
}
}
*sorry if it has sintaxys errors.... but thats the idea.
I try to display crystal report in Report.aspx. so for this first i create class "``report_class` and in that class i create function like this:
using cookies
in webform2 i try this
public static bool setCookiesValue(Page page, string cookiesName, string cookiesValue, ref string ermsg)
{
if (cookiesValue.Trim().Length < 1)
{
ermsg = "cookies empty";
return false;
}
HttpCookie clearCookies = page.Request.Cookies[cookiesName];
clearCookies[cookiesName] = cookiesValue;
clearCookies.Expires = DateTime.Now.AddDays(1d);
page.Response.Cookies.Add(clearCookies);
return true;
}
public static String getCookies(Page page, string cookiesName)
{
try
{
HttpCookie GetCookies = page.Request.Cookies[cookiesName];
return GetCookies[cookiesName].ToString();
}
catch (Exception er)
{
return string.Empty;
}
}
then on button click
protected void Button6_Click(object sender, EventArgs e)
{
try
{
string datef = string.Empty;
setCookiesValue(this, "fromdate", "todate","regiondrop", ref ret);
report_class r = new report_class();
Report_Detail report = new Report_Detail();
Response.Redirect("Reports.aspx");
}
catch
{
Label4.Visible = true;
}
}
and in reports.aspx
protected void Page_Load(object sender, EventArgs e)
{
Report_Detail report = new Report_Detail();
report_class r = new report_class();
string date_f = getCookies(this, "fromdate");
string date_t = getCookies(this, "todate");
string drop_r = getCookies(this, "regiondrop");
r.Bindreport_class(report, Convert.ToDateTime(date_f),
Convert.ToDateTime(date_t), Convert.ToString(drop_r));
CrystalReportViewer1.ReportSource = report;
CrystalReportViewer1.DataBind();
}
but this show error
Error 8 No overload for method 'setCookiesValue' takes 5 arguments
Error 3 The name 'getCookies' does not exist in the current context
You just need to pass the value from for Example form1 to form2:
Do it this way:
FORM2
public partial class Form2 : Form
{
public static Label lblvar= null;
public Form2()
{
InitializeComponent();
}
private void Form2_Load(object sender, EventArgs e)
{
}
}
FORM1:
public partial class Form1 : Form
{
public Form1()
{
Form2.lblvar = lblvarinform1;
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
lblvarinform1.Text = txtdatepicker.Text;
Form2.lblvar.Text = lblvarinform1.Text;
}
}
USING COOKIES:
public static bool setCookiesValue(Page page, string cookiesName, string cookiesValue,ref string ermsg)
{
if (cookiesValue.Trim().Length < 1)
{
ermsg = "cookies empty";
return false;
}
HttpCookie clearCookies = page.Request.Cookies[cookiesName];
clearCookies[cookiesName] = cookiesValue;
clearCookies.Expires = DateTime.Now.AddDays(1d);
page.Response.Cookies.Add(clearCookies);
return true;
}
public static String getCookies(Page page,string cookiesName)
{
try
{
HttpCookie GetCookies = page.Request.Cookies[cookiesName];
return GetCookies[cookiesName].ToString();
}
catch (Exception er)
{
return string.Empty;
}
}
using the function above:
set cookies new value:
string ret = string.Empty;
setCookiesValue(this,"yourcookiesname","thisisyourdatevaue_or_any",ref ret);
get cookies value in another form:
string getval = getCookies(this,"yourcookiesname");
I have a login form that have username and password.
Then if i successfully login i want to display the entered username on login form to MDIparent title bar/Status bar.
Example: MDIparent [ user name ]
You can just set the text property of the parent form from the child form.
this.MdiParent.Text = "MDIparent [" + username + "]";
you can create a class for user detail:
static class UserLogOn
{
private static string _userName = "";
private static string _fullName = "";
internal static string FullName
{
get { return _fullName; }
set { _fullName = value; }
}
internal static string UserName
{
get { return _userName; }
set { _userName = value; }
}
}
and then:
public partial class LoginForm : Form
{
private string username = "";
public LoginForm()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
//Do login processing and assuming success call the following;
UserLogOn.UserName = textBox1.Text;
username = textBox1.Text;
((Form1)this.Owner).Username = UserLogOn.UserName;
this.DialogResult = DialogResult.OK;
}
}
Here's some rough example code.
It assumes that your login dialog is modal and calls the login logic code (I have not fleshed it out). The login dialog does not care whether the parent is an MDI form or not.
It is two WinForms - this is the code section of them - I have only placed a button on the login form as I am only showing you how to pass back the data.
public partial class Form1 : Form
{
private string _username;
public Form1()
{
InitializeComponent();
this.OpenLoginForm();
}
public string Username
{
get
{
return this._username;
}
set
{ this._username=value;
this.Text=string.Format("Title string [{0}]", this._username);
}
}
private void OpenLoginForm()
{
LoginForm frm = new LoginForm();
frm.ShowDialog(this);
}
}
public partial class LoginForm : Form
{
private string username = "testnname";
public LoginForm()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
//Do login processing and assuming success call the following;
((Form1)this.Owner).Username = this.username;
this.DialogResult = DialogResult.OK;
}
}
Or you could have a property for Username on your login form and then use it as:
LoginForm frm = new LoginForm();
if (frm.ShowDialog() == DialogResult.OK)
{
this.Text = "Title text " + frm.Username;
}
Where
public partial class LoginForm : Form
{
public string Username { get; set; }
public LoginForm()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
//the login process has been successful
this.Username = "some user";
this.DialogResult = DialogResult.OK;
}
}
After log in, get the reference to the MDIparent(if you add some code with your question then how to do this may be specified as well). Then assign the entered name to the Test property of the parent form like this -
ParentReference.Text = usernameTextBox.Text;