C# - Avoid duplicating logic between WinForm and UserControl - c#

I found a question that I belive is what I was looking for, but there were certain things that I was not following in the answers. Therefore, I'd like to ask the question in a different way (Thanks for your patience). Here is the link I am referring to:
How to avoid duplicating logic on two similar WinForms?
OK. I have a dialog that I created. We've got controls for User Input, buttons to display other dialogs (to gain other input), etc. Aesthetically, I prefer the dialog with the controls laid out vertically. Anyhow, I was also thinking of creating a UserControl version of this dialog. This UserControl would have all the same controls, and all the same logic, but the controls would be laid out entirely different (more horizontal, then vertical).
So, I can't just create another (3rd) UserControl that I drop on the orignal form, and on the UserControl I want to create. (This 3rd UserControl would then contain all logic - thus, sharing between the two). I can't do this because of the different layouts.
I have no problem creating the two (Form, UserControl), with the controls laid out differently, but I don't want to 'cut-and-paste' all the logic from one to the other.
This does not seem like a case for MVP, or MVC. My model is the dialog itself. The dialog is intialized with some values, yes, but once initialized the "Model" becomes further User Input (which I then grab when they press the OK button).
Take for example this code (an event for one of my buttons on this dialog):
private void EditQuery_Click(object sender, EventArgs e)
{
try
{
EditQueryParameters();
}
catch (System.Exception ex)
{
// TODO: Write ErrMsg to Log file.
MessageBox.Show("Edit Query Parameters Error:\n\n" + ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
private void EditQueryParameters()
{
if (m_ReportType.QueryScoreDetails && optPickDetail.Checked)
{
// This brings up a different type of dialog
QueryDetails();
return;
}
// DateRange, StartDate, and EndDate are all saved from the last time
// I called this dialog
DateType DtType = new DateType(m_ReportType.DBDateRangeField,
m_DateRange, m_StartDate, m_EndDate);
// StartTime, EndTime too!
TimeType TmType = new TimeType(m_ReportType.DBTimeRangeField,
m_StartTime, m_EndTime);
List<AdvancedFilter> Filters = null;
if (lstAdvancedQuery.Items.Count > 0)
{
Filters = new List<AdvancedFilter>();
}
for (int i = 0; i < lstAdvancedQuery.Items.Count; ++i)
{
Filters.Add((AdvancedFilter)lstAdvancedQuery.Items[i]);
}
// QueryType is also saved from the last time I called QueryBuilder
QueryBuilder QryBuilder = new QueryBuilder(m_ReportType.DBCatalog, m_ReportType.DBTable,
m_QueryType, ref DtType, ref TmType, ref Filters);
// I am using Visual WebGUI, I have to do it this way
QryBuilder.Closed += new EventHandler(QryBuilder_Closed);
QryBuilder.ShowDialog();
}
I mean, I suppose I could have some "logic" class, which exposes something like:
public void EditQueryParameters(ref ReportType RptType, bool PickDetail,
string DateRange, DateTime StartDate, DateTime EndDate,
DateTime StartTime, DateTime EndTime, string QueryType)
{
if (ReportType.QueryScoreDetails && PickDetail)
{
// This brings up a different type of dialog
QueryDetails();
return;
}
DateType DtType = new DateType(ReportType.DBDateRangeField,
DateRange, StartDate, EndDate);
TimeType TmType = new TimeType(ReportType.DBTimeRangeField,
StartTime, EndTime);
// Yikes, more stuff to add to the signature of my method
// Will have to pull this outside the method and pass in Filters
List<AdvancedFilter> Filters = null;
if (lstAdvancedQuery.Items.Count > 0)
{
Filters = new List<AdvancedFilter>();
}
for (int i = 0; i < lstAdvancedQuery.Items.Count; ++i)
{
Filters.Add((AdvancedFilter)lstAdvancedQuery.Items[i]);
}
// QueryType is also saved from the last time I called QueryBuilder
QueryBuilder QryBuilder = new QueryBuilder(ReportType.DBCatalog, ReportType.DBTable,
QueryType, ref DtType, ref TmType, ref Filters);
// I am using Visual WebGUI, I have to do it this way
QryBuilder.Closed += new EventHandler(QryBuilder_Closed);
QryBuilder.ShowDialog();
}
There's a lot of set-up to use this method. I don't know, maybe I'm looking for something more .. "slick"?
On top of that, look at some (not all) of my init code (this is called from constructor or form_Load; it doesn't seem worth it to add this to the logic class, so that's all still "cut and paste" between the two):
private void InitializeUserDefinedTitle()
{
txtUserTitle.Text = m_UserTitle;
}
private void InitializePrintSelectionCriteria()
{
// Print Selection Criteria
chkSelectionCriteria.Checked = m_printSelectionCriteria;
}
private void InitializeTrendBy()
{
cmbTrend.Items.AddRange(Enum.GetNames(typeof(TrendBy)));
cmbTrend.SelectedIndex = (int)m_TrendBy;
cmbTrend.Visible = m_ReportType.TrendVisible;
lblTrend.Visible = m_ReportType.TrendVisible;
}
In summary, the original WinForm is a dialog that is intialized with data (constructor), is displayed to the user for input, when they OK the dialog that data is retrieved (and that data is stored outside the dialog, in member variables, for the next time they call the dialog - this is because we want to show what they last picked/entered).
That type of dialog I just described will also be a user control, and the logic should be shared between the two.
Thanks.

You can make two controls A and B, each containing the same buttons and/or other input controls arranged differently. Controls A and B will have identical properties, and events. The form (or third control) will contain the event handlers that allow the logic to be contained in only one place.
You can display either control A or B using the visible property or by adding one to the container.controls property, the container being the containing form or control.
And, for example, instead of having a handler for button1 in controls A and B that handles the complete logic of the button press, the handlers for button1 in control A and B would just raise an event that will be handled by the container of control A or B.

Instead of encapsulating the logic, I would encapsulate the layout. Use a property of the user control to specify which layout yout want. Then wherever it is (standalone form, one of three instances on the same form, whatever) you access it and specify the layout the same way.
As for how to encapsulate the layout, there are a bunch of possibilities. You could just do it programatically, i.e. write each version of the layout code. (The programamatic version would be cleaner if you used some kind of layout containers, like the Panels in WPF.) You could draw the layout in a designer, and copy the generated code. The different versions of the layout logic could be stuffed into private methods, or encapsulated into objects.

Related

Logic for filling a dropdown is needed twice

I have two pages sharing the same Dropdown control which need the same logic for filling the Dropdown. The code looks like:
private void FillDropDown(Guid indentifier)
{
DateTime start = GetStartFromSession;
DateTime end = GetEndFromSession;
List<DataToDisplay> dataToDisplay = Businesslogic.GetData(identifier, start,end);
dataToDisplay.Add(new DataToDisplay(){ID : Guid.Empty, Value: GetLocalResourceString("PleaseSelectText");
//some more logic....
dropDown.DataSource = dataToDisplay;
dropDown.DataBind();
}
The code is exactly the same in two pages. I am not a fan of creating a helper class which needs the Businesslogic, the control to fill etc. But as code duplication is bad, i don't like the current solution also. I was thinking about creating a new generic control but its only a Dropdownbox, nothing more.
Any ideas?
Thanks

ObjectListView editing doesn't work

I'm trying to create a simple listbox with ObjectListView (WinForm, C#). The goal is to have a single value (a double) and a check box.
I want to be able to edit the double value by Single Click, so here are the relevant lines of code from my MyWindow.Designer.cs file (i've left out the default values for efficiency):
this.olvDepths = new BrightIdeasSoftware.ObjectListView();
this.olvColumn1 = ((BrightIdeasSoftware.OLVColumn)(new BrightIdeasSoftware.OLVColumn()));
...
this.olvDepths.CellEditActivation = BrightIdeasSoftware.ObjectListView.CellEditActivateMode.SingleClick;
this.olvDepths.CheckBoxes = true;
this.olvDepths.CheckedAspectName = "IsDefault";
this.olvDepths.FullRowSelect = true;
//
// olvColumn1
//
this.olvColumn1.AspectName = "Depth";
this.olvColumn1.Text = "";
this.olvColumn1.IsEditable = true;
I then create a list of my class (ShieldingEntry) and use the olvDepths.SetObjects() with the list. My ShieldingEntry class looks like this:
public class ShieldingEntry
{
public double Depth { get; set; }
public bool IsDefault { get; set; }
}
However, when I click the field, it doesn't go into edit mode. I've also tried the DoubleClick, SingleClickAlways, and F2Only modes and they don't work either.
The Checkbox works fine.
************** I have additional information *********************
I've pulled and build the ObjectListView source, so I could step through it.
I put a breakpoint in the OLV StartCellEdit method and it gets called and appears to setup and select the control appropriately. It just never appears...
As I noted in the comments on the answer below, I've got this control on a tabbed dialog, and if I switch to another tab, then back, the control works fine.
What am I missing?
I've used ObjectListView before, and here is what I had to do:
Handle the CellEditStarting event. This event is raised when the cell goes into edit mode. Since OLV doesn't really have built-in editors, you have to make your own. Then handle the CellEditFinishing event to validate the data before putting it back into your model.
So first, handling the CellEditStarting event:
private void objlv_CellEditStarting(object sender, CellEditEventArgs e)
{
//e.Column.AspectName gives the model column name of the editing column
if (e.Column.AspectName == "DoubleValue")
{
NumericUpDown nud = new NumericUpDown();
nud.MinValue = 0.0;
nud.MaxValue = 1000.0;
nud.Value = (double)e.Value;
e.Control = nud;
}
}
This creates your editing control. If you want to make sure the size is right, you can set the size of the control (in this case a NumericUpDown) to the cell bounds using e.CellBounds from the event object.
This will show the editor when you click in the cell. Then you can handle the editor finished event to validate the data:
private void objlv_CellEditFinishing(object sender, CellEditEventArgs e)
{
if (e.Column.AspectName == "DoubleValue")
{
//Here you can verify data, if the data is wrong, call
if ((double)e.NewValue > 10000.0)
e.Cancel = true;
}
}
I don't think handling it is required, but its good practice to validate data from the user.
The editing control in the CellEditStarting event can be any control, even a user defined one. I've used a lot of user defined controls (like textboxes with browse buttons) in the cell editor.
[Edit]
I uploaded an example here dropbox link that seems to work. Might not be in the exact view as needed, but seems to do the job.
For anyone else with this problem. I had it specifically when trying to edit a 'null' value in a decimal? on the OLV on a tab page. Solution for me was to set UseCustomSelectionColors to 'False'. I didn't look elsewhere to see if it was reported as a bug. Seems like a bug.

How to access the Items of a User Control

I have a C# Form that prints multiple instances of a User Control. Let's say that the form prints 5 instances of the User Control (Please see the link attached). How can I store/save the data inputted in all User Controls? Thanks
Here is the screenshot of the C# Form:
You'll have to store the User Controls when you instantiate them in a List or something.
You could have a class like this:
class SomeUC : UserControl
{
public SomeUC()
{
}
// A public method.
public string GetData()
{
return textBox1.Text;
}
}
Where textBox1 is the Name of a TextBox in your SomeUC
And then inside your main or something.
// Instantiate a List that will hold your UserControls, this has to be outside all methods
List<SomeUC> list = new List<SomeUC>();
// And now when you want to build your UCs
// Instantiate your UserControl
SomeUC uc1 = new SomeUC();
// Store your UserControl in a List or something (Can't help you with that)
list.Add(uc1);
Add as much as you want.
A List is not the only way you can do that, but since you don't know how many UserControls you're going to build beforehand, it makes since to use a List.
And then you can access them from the list by their index.
SomeUC uc1 = list[0];
string data = uc1.GetData();
This is an example of accessing one control (the TextBox) in your SomeUC. For other classes (such as the ComboBox) the interaction is different. Meaning you won't have a Text property in the ComboBox. You'll have to figure out things like that on youself. A little research is what it takes. You can always come back if you couldn't find a solution for something.
You can create a property like this for each item in user control.
public string DG
{
get
{
return txtDG.Text;
}
set
{
txtDG.Text = value;
}
}
Then you can access the control value by using following line in your form.
supposed you have created a usercontrol MyControl and you have placed some object of this control in FlowLayoutPenal (pnlFLP).
To get value from control
string DG = ((MyControl)pnlFLP.Controls[0]).DG;
To set value in control
((MyControl)pnlFLP.Controls[0]).DG = "1";
Try this code for accessing user control in the page
Dim txtName As TextBox = TryCast(UserControlName.FindControl("txtName"), TextBox)

Keeping track of 40+ control values

I am in need of some guidance for the following design.
I have a tab control that contains various group boxes. Within the group box, there are specific controls that relates to that group box. For example:
Now whenever a change is made to any control in the group box, the value for the control needs to be tracked because at the end of the application run cycle, the control data will need to be saved to a file that contains that value. An example file is:
HOT_STANDBY_FEATURE_ENABLE [val from control here]
HEART_BEAT_DIGITAL_OUTPUT [val from control here]
....
A design that I have in mind has another that has just properties that the group box form sets whenever a ValueChanged event occurs on a control.
Example code:
class ConfigurationValues
{
public int HotStandbyValue { get; set; }
public int HeartBeatDigitalOutputValue { get; set; }
//...add all other controls here
}
The downside that I see to this is that there are 40 controls on that tab page, so I'd have to manually type each property. When the file needs to be generated at the end of the application run cycle, I have a method that gets the value of the control need.
Example:
private void GenerateFile()
{
string[] file =
"HOT_STANDBY_FEATURE_ENABLE " + ConfigurationTabSettings.HotStandbyValue;
}
Another design consideration I need to make is that whenever a user clicks "Open Configuration File", the values from the file from disk need to be loaded into the properties so the form can take that data on startup and populate the controls within the group boxes with their respective values.
Any suggestions on this design would be greatly appreciated. I know this is not the most efficent way to do this and am not the most experienced programmer, so any Google keywords I can search for would be great also.
You could xml serialise and xml deserialise your ConfigurationValues class rather than writing manual "generate file" and "read file" methods
http://support.microsoft.com/kb/815813
You'll need to bind the controls Text or Value properties to the properties in your ConfigurationValues class e.g.
ConfigurationValues cv = Repository.ReadConfigValues();
numPulseFilterDelay.DataBindings.Add("Value", cv, "PulseFilterDelay");
// Add the rest of your control bindings here
on the btnSave_Click() of your Form, end the current edit on the form and save the config values
void btnSave_Click(object sender, EventArgs e)
{
BindingContext[cv].EndCurrentEdit(); // Commits all values to the underlying data source
Repository.SaveConfigValues(cv);
}
In your repository class you'll need methods to Load() and Save() the data. You can put XmlSerialization code in here, or write your own format (depending on your requirements)
public class Repository
{
public static ConfigurationValues LoadConfigValues()
{
var cv = new ConfigurationValues();
string[] lines = File.ReadAllLines("values.cfg");
foreach (string cfg in lines)
{
string[] nameValue = cfg.Split(new char[] { ' ' } ); // To get label/value
if (nameValue[0] == "HOT_STANDBY_FEATURE_ENABLE")
cv.HotStandbyFeatureEnable = nameValue[1];
else if (nameValue[0] == "SOME_OTHER_PROPERTY")
cv.SomeOtherProperty = nameValue[2];
// Continue for all properties
}
return cv;
}
public static void SaveConfigValues(ConfigurationValues cv)
{
var builder = new StringBuilder();
builder.AppendFormat("HOST_STANDBY_FEATURE_ENABLE {0}\r\n", cv.HostStandbyFeatureEnable);
// Add the rest of your properties
File.WriteAllText("values.cfg", builder.ToString());
}
}

Moving data between two user controls in WinForm Application

As a course project i'm building a form in c# which contains two user controls.
The first user control has a checkedlistbox and the second control has also a checkedlistbox when the first control checkedlistbox will contain list of people (male/female) and the second user control the checkedlistbox will have two options: male, female and when I click a button on the first control which says: "update friends" it's suppose to go to the second control and check if we selected male or female and according to that to update the checkedlistbox in the first user control with friends by gender type by what was selected on the second control.
Basically I want to raise an event every time the button on the first control selected then to get the data from the second control to the first control.
Is it possible to do so between two controls who are inside a form and are different controls?
Any help will be appriciated.
Thanks.
To do this "correctly," you would want to use something like the MVC architecture. It's definitely a lot more work initially to understand and implement but is very useful to know if you plan on doing any serious UI application development. Even if you don't go all the way with it, the concepts are useful to help design even "quick and dirty" applications.
Define your data model without thinking in terms of the UI, e.g.:
internal enum Gender
{
Male,
Female
}
internal class Person
{
public Gender Gender { get; set; }
public string Name { get; set; }
}
// . . .
// Populate the list of people
List<Person> allPeople = new List<Person>();
allPeople.Add(new Person() { Gender = Gender.Male, Name = "Xxx Yyy" });
allPeople.Add(new Person() { Gender = Gender.Female, Name = "Www Zzz" });
// . . .
For the view portion, you would typically use data binding on the UI controls so that the controls will automically reflect changes to the underlying data. However, this can get difficult especially if you are not using a database-like model (e.g. System.Data.DataSet). You may opt to "manually" update the data in the controls which might be fine in a small app.
The controller is the portion that uses the UI events and makes changes to the model, which may then be reflected as changes in the view.
internal class Controller
{
private Gender selectedGender;
private List<Person> allPeople;
private List<Person> friends;
public Controller(IEnumerable<Person> allPeople)
{
this.allPeople = new List<Person>(allPeople);
this.friends = new List<Person>();
}
public void BindData(/* control here */)
{
// Code would go here to set up the data binding between
// the friends list and the list box control
}
// Event subscriber for CheckedListBox.SelectedIndexChanged
public void OnGenderSelected(object sender, EventArgs e)
{
CheckedListBox listBox = (CheckedListBox)sender;
this.selectedGender = /* get selected gender from list box here */;
}
// Event subscriber for Button.Click
public void OnUpdateFriends(object sender, EventArgs e)
{
this.friends.AddRange(
from p in this.allPeople
where p.Gender == this.selectedGender
select p);
// If you use data binding, you would need to ensure a
// data update event is raised to inform the control
// that it needs to update its view.
}
}
// . . .
// On initialization, you'll need to set up the event handlers, etc.
updateFriendsButton.Click += controller.OnUpdateFriends;
genderCheckedListBox.SelectedIndexChanged += controller.OnGenderSelected;
controller.BindData(friendsListBox);
// . . .
Basically, I recommend not having controls talk directly, but rather through a controller-like class as above which has knowledge of the data model and the other controls in the view.
Of course it's possible: you need to make the link between the 2 controls in the form.
Just declare an event 'ButtonClicked' in control #1
Then make a public method 'PerformsClick' on the control #2
And in the form, in the constructor, after the call to InitializeComponent, link the event from the control #1 to the method to the control #2:
control1.ButtonClicked += delegate(sender, e) {
control2.PerformsClick();
};
(I type on the fly to give you an idea, it'll surely not compile)
If you want to pass any data, just add parameters in the PerformsClick method.

Categories

Resources