Reputation: 1022
I usually in my web projects use one webform for adding and update data. I just scratched winforms environment so I was thinking to use same approach one form to add and update data.
I was thinking to use two constructors on addEditForm like
public AddEditForm()
{
.. to do new object
}
public AddEditForm(MyDataObj obj)
{
... to do edit
}
so, is this right approach or is there better practice?
thanks
Upvotes: 1
Views: 68
Reputation: 6159
The correct approach would be:
public partial class CustomerForm: Form
{
private object instance;
public CustomerForm()
{
InitializeComponent();
SetData(BLL.CreateNewEmptyObject());
}
public CustomerForm(object details)
: this()
{
SetData(details);
}
public void SetData(object details)
{
instance = details;
//bind the details to controls
}
private void Save()
{
BLL.Save(instance);
}
public bool EnableEdit {get{...
}
Usage Examples:
var newCustomerFrm = new CustomerForm();
var existingCustomerFrmReadOnly = new CustomerForm(BLL.GetCustomerById("123"))
{
EnableEdit = false
};
var existingCustomerFrmToEdit = new CustomerForm(BLL.GetCustomerById("123"))
{
EnableEdit = true
};
Upvotes: 0
Reputation: 2488
As I said in my comment I use this approach too, of course when I'm not using MVP(which is a different story)
About calling InitializeComponent() you need it in your form construction because it is the method which (as you can tell from it's name) initializes your form and controls on it and without it you'll get an empty form.
But if you are concerned about calling InitializeComponent() twice, I prefer this:
MyDataObj _myObject;
public AddEditForm()
{
InitializeComponent();
}
public AddEditForm(MyDataObj obj)
:this()
{
if(obj == null) //you're creating the object
_myObject = new MyDataObj();
else // you're editing it
_myObject = obj;
}
// Continue my work with _myObject
Upvotes: 2
Reputation: 2541
You can create different constructors in the following way:
MyDataObj editItem=null;
public AddEditForm()
{
InitializeComponent();
//Other common code for initialization.
}
public AddEditForm(MyDataObj obj) : this()
{
editItem = obj;
//Other code specific to editing.
}
If the object editItem
is null, then the form can be considered in Add mode, otherwise Edit mode.
A property also can be made for the same For example:
public bool IsEditMode
{
get
{
return (editItem != null);
}
}
hope it helps...
Upvotes: 2
Reputation: 1887
The approach you posted is the normal approach for creating such a form.
But sometimes you will see something like this.
public AddEditForm(MyDataObj obj, int mode) //1 = edit, 2 = create
{
... to do edit
}
If you think about it, this is not a good alternative. It's harder to understand and looks ugly.
Do I need to call InitializeComponent() in every constructor?
Unless you do constructor chaining (which would not work here), yes you do. Please look @Virus answer for a way to only call it once.
Upvotes: 0