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.
Related
I wan to click button which created in web page.
I added following code to the my project but it did execute, string always null.
public partial class MainPage : ContentPage
{
public MainPage()
{
InitializeComponent();
wbWeb.Source = "https://www.facebook.com";
}
private async void btnBrowser_Clicked(object sender, EventArgs e)
{
string str = wbWeb.EvaluateJavaScriptAsync($"document.getElementById('loginbutton').click();");
//str is null
}
}
I am facing a problem with the update of a list that is filtered depending on the value of a dropdown.
This is a description of my model:
I have a list of users
When I click on a user, another list of orders of this user is
displayed
The list of orders is filtered according to the value of a dropdown
containig a list of status
Please, see the image below:
Users With orders
The filter is working well, but the problem that I am facing is that once I choose an element from the dropdown, the list of orders is no longer updated when the user is changed.
This is a snippet of my code:
Construction of the Order Panel and instantiation of the list:
public OrdersPanel(String id)
{
super(id);
this.setOutputMarkupId(true);
setOutputMarkupPlaceholderTag(true);
IModel<List<Order>> orderListModel = new OrderListModel();
orderListView = new orderListView("orderListView", orderListModel);
//...
}
OrderListModel:
private final class OrderListModel extends LoadableDetachableModel<List<Order>> {
private static final long serialVersionUID = 1L;
#Override
protected List<Order> load() {
//...
//We set the variable allOrders in order to be used later in the filtering process
//...
}
}
Construction of the dropdown:
private class StatusDropDown extends CustomDropDown<String> implements IAjaxIndicatorAware {
private static final long serialVersionUID = 1L;
private StatusDropDown(String id) {
super(id);
this.setNullValid(true);
StatusListModel statusModel = new StatusListModel();
setChoices(statusModel);
setChoiceRenderer(new StatusChoiceRenderer(statusModel));
}
#Override
protected void onUpdate(AjaxRequestTarget target) {
super.onUpdate(target);
if (target != null) {
new StatusDropDownRefreshEvent(this, target).fire();
target.addComponent(this);
}
}
/**
* disable ajax marker for the form fields
*/
public String getAjaxIndicatorMarkupId() {
return null;
}
}
CustomDropDown (Must be used by the context of the project on which I am working):
public class CustomDropDown<V> extends DropDownChoice<V> {
private static final long serialVersionUID = 1L;
public CustomDropDown(String id) {
this(id, id);
}
public CustomDropDown(String id, String property) {
super(id);
setOutputMarkupId(true);
setModel(new CustomComponentPropertyModel<V>(property));
add(new AjaxFormComponentUpdatingBehavior("onchange") {
private static final long serialVersionUID = 1L;
#Override
protected void onUpdate(AjaxRequestTarget target) {
new UpdateEvent(CustomDropDown.this, target).fire();
if (target != null) {
target.addComponent(CustomDropDown.this);
}
CustomDropDown.this.onUpdate(target);
}
});
}
#Override
protected void onComponentTag(ComponentTag tag) {
super.onComponentTag(tag);
if (!isValid()) {
tag.append("class", "invalid", " ");
FeedbackMessage message = getFeedbackMessage();
if (message != null) {
tag.put("title", message.getMessage().toString());
message.markRendered();
}
} else if (isRequired()) {
tag.append("class", "red-background", " ");
}
}
public void setWidth(String width) {
this.add(new AttributeAppender("style", true, new Model<String>("width:" + width), ";"));
}
public CustomDropDown<V> setChoices(V... choices) {
this.setChoices(Arrays.asList(choices));
return this;
}
protected void onUpdate(AjaxRequestTarget target) {
}
}
StatusDropDownRefreshEvent listener:
#AjaxUpdateEventListener
public void statusDropDownRefreshPanel(StatusDropDownRefreshEvent event){
if (event.getTarget() != null) {
orderListView.setList(getOrdersByStatus(allOrders));
event.getTarget().addComponent(this);
}
}
Changing of the user:
When the user is changed, an update event is fired from the users panel, and then cached in the orders panel:
#AjaxUpdateEventListener
public void refreshPanel(CustomerOrderRefreshEvent event) {
if (event.getTarget() != null) {
event.getTarget().addComponent(this);
this.onBeforeRender();
}
}
onBeforeRender() to determin the visibility of the panel (if no order is available then the orders panel is not visible)
#Override
public void onBeforeRender() {
setVisibilityAllowed(checkVisibility());
super.onBeforeRender();
}
Finally, the checkVisibility Method:
private boolean checkVisibility() {
if (isUserChanged()) {
List<Order> src = orderListView.getModelObject();
statusDropDown.setDefaultModelObject(null);
return CollectionUtils.isNotEmpty(src);
}
return true;
}
My main problem is that the changing of the selected user doesn't update the list of orders once a status is chosen from the list.
Thank you very much for your replies and your time.
Best regards.
I found a solution to my problem.
The list of orders wasn't updated because The method getObject was called on the wrong object.
The call of the load() method can be done via getObject(), but the condition is: The object must be detached (See the implementation of getObject() at this link)
The detached object in my case is the orderListModel and not the orderListView, so this is what I added to my code:
//Set the content of the list model
List<Order> orders = orderListModel.getObject(); //This invokes the load method
//Update the content of the list
orderListView.setList(orders);
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
i have created a sample view in eclipse using the following code.i want the view to be
automatically refereshed.the part of code in quotes "" gives refresh option but it is done
manually.can anyone help me know how it can be done automatically
public class SampleView extends ViewPart {
public static final String ID = "tab.views.SampleView";
private TableViewer viewer;
class ViewContentProvider implements IStructuredContentProvider {
public void inputChanged(Viewer v, Object oldInput, Object newInput) {
}
public void dispose() {
}
public Object[] getElements(Object parent) {
return new String[] { "Status of your hudson build is: " +hudson.d};
}
}
class ViewLabelProvider extends LabelProvider implements ITableLabelProvider {
public String getColumnText(Object obj, int index) {
return getText(obj);
}
public Image getColumnImage(Object obj, int index) {
return getImage(obj);
}
public Image getImage(Object obj) {
return PlatformUI.getWorkbench().
getSharedImages().getImage(ISharedImages.IMG_OBJ_ADD);
}
}
public SampleView() {
}
public void createPartControl(Composite parent) {
viewer = new TableViewer(parent, SWT.MULTI | SWT.H_SCROLL | SWT.V_SCROLL);
viewer.setContentProvider(new ViewContentProvider());
viewer.setLabelProvider(new ViewLabelProvider());
viewer.setInput(getViewSite());
PlatformUI.getWorkbench().getHelpSystem().setHelp(viewer.getControl(), "Tab.viewer");
hookContextMenu();
}
" private void hookContextMenu() {
MenuManager menuMgr = new MenuManager("#PopupMenu");
Menu menu = menuMgr.createContextMenu(viewer.getControl());
viewer.getControl().setMenu(menu);
Action refresh =new Action() {
public void run() {
// initialize();
viewer.refresh();
}
};
refresh.setText("Refresh");
menuMgr.add(refresh);
}"
public void setFocus() {
viewer.getControl().setFocus();
}
}
It is only possible to refresh the tree contents automatically, if you fill it using JFace Data Binding, that would not work with remote build results.
I recommend either using a model with notification support: when the model changes, its listeners are notified. Then your view could listen for these notifications and refresh itself.
If for some reason this is not possible, you have to poll your models manually. For that I recommend creating a Job that is executed in the background automatically (its last step is to reschedule itself some times later), that checks whether the model changed and refreshes the view.
I am trying to achieve an update form.
I use a library to open a form when there is an updated file and download using edtFTPNet
In the form I pass the FTP object and start download, in FormLoad i handle two events and i use Thread to StartDownload(). My two events never invoking, i use them to set a progress bar.
public partial class UpdateProgressForm : XtraForm
{
public FTPConnection FtpConn { get; set; }
public string UpdateFileName { get; set; }
public UpdateProgressForm()
{
InitializeComponent();
}
private void OnLoad(object sender, EventArgs e)
{
FtpConn.Downloading += FileDownLoading;
FtpConn.BytesTransferred += FileBytesTransfered;
}
private void FileDownLoading(object sender, FTPFileTransferEventArgs e)
{
progressBar.Properties.Maximum = (int) e.FileSize;
}
private void FileBytesTransfered(object sender, BytesTransferredEventArgs e)
{
progressBar.Position = (int) e.ByteCount;
}
public void StartDownload()
{
FtpConn.DownloadFile(#".\" + UpdateFileName, UpdateFileName);
}
private void OnShown(object sender, EventArgs e)
{
Thread tt = new Thread(StartDownload) {IsBackground = true};
tt.Start();
}
}
Library method calling the Form:
private void DownloadUpdateFile(string updateFileName)
{
using (ProgressForm = new UpdateProgressForm { FtpConn = FtpConn, UpdateFileName = updateFileName })
{
ProgressForm.ShowDialog();
}
}
Any help? Thank you.
Take a look in the designer and make sure you subscribe to those events
Make sure you Instanciate and Show the from from the Main Thread.
Are you sure that the event handlers are not invoked? I think your problem rather is that you try to update the progress bar on the worker thread on which the event handlers are invoke (which is not the thread on which the GUI was created). You should make sure that the GUI updates are performed on the correct thread:
private void FileDownLoading(object sender, FTPFileTransferEventArgs e)
{
progressBar.Invoke((MethodInvoker) delegate
{
progressBar.Properties.Maximum = (int) e.FileSize;
});
}