I have two form in my C# base desktop application.
And i wants to pass my id in one form to another form.
In asp.net we use query string to pass the value for one page to second page but in C# base desktop application what i use?
Please help me.
Thank you.
Properties or constructor arguments:
1) Properties
partial class Form2 {
public int ID { get; set; }
// ...
}
Form2 newForm = new Form2() { ID = id_here };
2) Constructor argument:
partial class Form2 {
private int _id;
public Form2(int id) {
this._id = id;
}
// ...
}
Form2 newForm = new Form2(id_here);
Just create public property:
On your Form1:
partial Class Form1()
{
private void Button1_Click(object sender, EventArgs e)
{
Form2 frm2 = new Form2(){passMessage="Test1"};
frm2.Show();
this.hide();
}
}
On your Form2:
partial Class Form2()
{
public string passMessage;
private void ButtonShowMessage_Click(object sender, EventArgs e)
{
MessageBox.Show(passMessage);
}
}
Regards
Related
im trying to passing a class which preserves the values in it across all forms. but i have no idea how to do it.
my default class:
namespace bankaccount
{
class Account
{
private string _name, _accountNo, _accountType;
private double _balance = 0;
public string Name
{
get{ return _name;}
set{ _name = value;}
}
public string AccountNo
{
get { return _accountNo; }
set { _accountNo = value; }
}
public string AccountType
{
get { return _accountType; }
set { _accountType = value; }
}
public double Balance
{
get { return _balance; }
set { _balance = value; }
}
public Account()
{
}
public Account(string name, string accountNo, string accountType, double balance)
{
_name = name;
_accountNo = accountNo;
_accountType = accountType;
_balance = balance;
}
public double withdraw(double withdraw)
{
return _balance = _balance - withdraw;
}
public double deposit(double deposit)
{
return _balance = _balance + deposit;
}
}
}
main menu form:
public partial class frmMainMenu : Form
{
public frmMainMenu()
{
InitializeComponent();
}
public void btnNewAccount_Click(object sender, EventArgs e)
{
this.Hide();
frmNewAccount NewAccount = new frmNewAccount();
NewAccount.Show();
}
public void btnDeposit_Click(object sender, EventArgs e)
{
this.Hide();
frmDeposit Deposit = new frmDeposit();
Deposit.Show();
}
public void btnWithdraw_Click(object sender, EventArgs e)
{
this.Hide();
frmWithdraw Withdraw = new frmWithdraw();
Withdraw.Show();
}
public void btnBalance_Click(object sender, EventArgs e)
{
this.Hide();
frmBalance Balance = new frmBalance();
Balance.Show();
}
}
New Account form (form to create object from the class)
public partial class frmNewAccount : Form
{
public frmNewAccount()
{
InitializeComponent();
}
private void btnRegister_Click(object sender, EventArgs e)
{
//Account newAccount = new Account();
string name = string.Copy(txtName.Text);
string accountNo = string.Copy(txtAccountNo.Text);
string accountType = string.Copy(txtAccountType.Text);
double amount = double.Parse(txtAmount.Text);
Account newAccount = new Account(name, accountNo, accountType, amount);
}
private Account btnMainMenu_Click(object sender, EventArgs e)
{
this.Hide();
frmMainMenu MainMenu = new frmMainMenu();
MainMenu.Show();
}
}
Deposit form
public partial class frmDeposit : Form
{
public frmDeposit()
{
InitializeComponent();
}
private void btnDeposit_Click(object sender, EventArgs e)
{
}
private void btnMainMenu_Click(object sender, EventArgs e)
{
this.Hide();
frmMainMenu MainMenu = new frmMainMenu();
MainMenu.Show();
}
}
what im trying to do here is create Account newAccount on New Account Form, using the data its created to be accessible in another form...
Your code has to be changed minimally to give this reference of an account to a child form. I would do it explicitly in constructor.
public partial class frmDeposit : Form
{
Account _account;
public frmDeposit(Account account)
{
_account = account;
InitializeComponent();
}
(...)
After this you can use inside the frmDeposit class the _account field.
This approach is typically better than using a property as you enforce the form to be initialized with an account.
And when you create your dialog to set deposit information, you will have to write instead of:
var depositForm = new frmDeposit(); //here you will get compilation error
depositForm.ShowDialog()
You will have to write:
var depositForm = new frmDeposit(account); //compilation error is fixed
depositForm.ShowDialog()
You usually don't pass classes, but instances (i.e. objects). Create an instance of the class in the form that starts your workflow. In every child form that's called, add a property
public BankAccount Account { get; set; }
and set the value of that property before showing the child form.
using (FrmChildForm frm = new FrmChildForm())
{
frm.Account = myBankAccount;
...
}
Another solution would be to create an instance variable in every child form as well and pass the account in the constructor:
using (FrmChildForm frm = new FrmChildForm(myBankAccount))
...
public class FrmChildForm : Form
{
private BankAccount _account;
public FrmChildForm(BankAccount theAccount)
{
_account = theAccount;
}
}
About your navigation
You're doing it wrong! You're filling up memory for nothing, creating instances over and over the place. Why?
Well, your main menu creates a child form, then hides itself. Your child form then generates a new main menu instead of just closing itself and showing the existing main form again! That's highly inefficient and prevents you from keeping the account instance I talked about above.
What you should do is this:
public void btnNewAccount_Click(object sender, EventArgs e)
{
frmNewAccount NewAccount = new frmNewAccount();
NewAccount.Account = myAccount;
NewAccount.FormClosing += SubFormClosing;
NewAccount.Show();
this.Hide();
}
Then, have a method SubFormClosing:
private void SubFormClosing(object sender, FormClosingEventArgs e)
{
this.Show();
}
Then, the code to return to the main form comes down to:
private void btnMainMenu_Click(object sender, EventArgs e)
{
this.Close();
}
This creates one main menu. Upon selecting an module, the module window is opened, the main menu is hidden. Instead of creating a new main menu when closing the module window, the old main menu is restored when the module window is closed.
The trick here is to attach an event handler to the closing event of the module form so the hidden menu form gets notified that it should show itself again.
And you should learn about modal dialogs. The "window" where a new account is created should actually be a modal dialog that collects the information. Then, the main menun sets its myAccount member variable based on the new account information. There's no need to pass the account to the "New Account" mask, as it creates a new account.
Can someone please tell me where I'm going wrong. I have an action with the following custom filter attribute...
[UserValidation("Standard")]
public ActionResult Index()
The custom attribute is defined as...
public class UserValidationAttribute : FilterAttribute, IAutofacActionFilter
{
public ILogger Logger { get; set; }
private string _status;
public UserValidationAttribute (string status)
{
// At this point in the code, 'Logger' is null
_status = status;
}
public void OnActionExecuting(HttpActionContext actionContext)
{
}
public void OnActionExecuted(HttpActionExecutedContext actionExecutedContext)
{
}
}
And I'm building the AutoFac container as...
var builder = new ContainerBuilder();
builder.RegisterControllers(Assembly.GetExecutingAssembly());
builder.Register(x => new Logger()
.As<ILogger>()
.InstancePerHttpRequest();
builder.RegisterFilterProvider();
var container = builder.Build();
System.Web.Mvc.DependencyResolver.SetResolver(new AutofacDependencyResolver(container));
and for some reason when the custom action filter's constructor is 'hit', the public 'Logger' property is null?
Any help would be appreciated.
Thanks
I have inherited some struts2 REST-plugin based code, and the following construct puzzles me:
#Namespace("/merchants/{id}")
public class MerchantAction extends ActionSupport implements ModelDriven<Object> {
private Merchant merchant = new Merchant(); // A Model
private Iterable<Merchant> merchants; // A list of models
....
public HttpHeaders index() {
merchants = merchantService.findAllMerchants();
return new DefaultHttpHeaders("index");
}
#Override
public Object getModel() {
return (merchant != null ? merchant : merchants);
}
public void setId(String id) {
merchant = merchantService.findMerchant(id));
}
In other words, it seems to be toggling between returning a list and returning an individual item in the getModel() call. Is this kosher ? Looks a bit strange to me
I've considered your approach, but finally gave it up. IMO, it lost the advantage of strong typed action.
My solution is, creating a ViewModel for each action. In the view models, there can be the single model, the list of the model, and other items for pages usage, such as items for drop down list or radio buttons.
So the UserViewModel is like:
public class UserViewModel implements IViewModel<User> {
private User model;
private List<User> list;
public void setModel(User user) {
this.model = user;
}
public User getModel() {
return model;
}
public void setList(List<User> list) {
this.list = list;
}
public List<User> getList() {
return list;
}
}
And the actions are like:
public class UserController implements ModelDriven<UserViewModel> {
private int id;
private UserViewModel model = new UserViewModel();
public String index() {
return "success";
}
public String show() {
return "success";
}
public void setId(int id) {
this.id = id;
}
public int getId() {
return this.id;
}
#Override
public UserViewModel getModel() {
return model;
}
}
But in this way, I still lose the shortcut way in jsp files. I should write long model.userName instead of short userName.
I'm still finding the best solution of it.
I found this sample but its for web. Can any one check this proj. and add a simple sample using winforms(no wpf).
Source Code
Thx
What kind of problem were you facing? Anyways I have made sample (yet basic) structure of how you can achieve this in WinForm. I have done using sort of Model View Presenter pattern.
First of all we have a presenter, which would deal with unit of work almost similarly the way controller does
internal class EmployeePresenter
{
private readonly IEmployeeFormView _employeeFormView;
private readonly IUnitOfWork _unitOfWork;
public EmployeePresenter(IEmployeeFormView view)
{
_employeeFormView = view;
_unitOfWork = new SqlUnitOfWork();
}
internal void GetData()
{
var id = 1; //parameter
var employee = _unitOfWork.Employees.Single(e => e.Id == id);
_employeeFormView.PopulateData(employee.Name);
}
}
Then we have an interface and a form implementing that interface
public interface IEmployeeFormView
{
void PopulateData(string data);
}
public partial class EmployeeForm : Form, IEmployeeFormView
{
private readonly EmployeePresenter _presenter;
public EmployeeForm()
{
InitializeComponent();
_presenter = new EmployeePresenter(this);
}
#region IEmployeeFormView Members
public void PopulateData(string data)
{
txtName.Text = data; //txtName is a textbox on form
}
#endregion
private void btnGet_Click(object sender, EventArgs e)
{
_presenter.GetData();
}
}
Add the required reference and you are done. This might not be the best way but it's certainly a way to achieve this.
Solution is upload here.
Hope this helps. Please feel free to discuss, if required.
I am facing a situation in which both the codebehind file of an ASPX master page and that of a regular ASPX page that does not use the master implement an interfance. The implementation is exactly the same.
Is it possible to make the two codebehinds share the implemenation instead of each has its copy of the same implementation? If yes, how should I approach this?
Thank you in advance for any insight.
John
How about using composition, on which both, the Master and the ASPX page have a reference to a class that implements the interface?
public interface IFace
{
int MyProperty { get; set; }
void MyMethod(string pVariable);
}
[Serializable]
public class ClassA:IFace
{
public ClassA()
{
}
#region IFace Members
public int MyProperty
{
get
{
throw new NotImplementedException();
}
set
{
throw new NotImplementedException();
}
}
public void MyMethod(string pVariable)
{
throw new NotImplementedException();
}
#endregion
}
public partial class MasterPage : System.Web.UI.MasterPage
{
private ClassA IntefaceImplementor = new ClassA();
protected void Page_Load(object sender, EventArgs e)
{
}
}
public partial class _Default : System.Web.UI.Page
{
private ClassA InterfaceImplementor = new ClassA();
protected void Page_Load(object sender, EventArgs e)
{
}
}