Setting a default value on form start for DomainUpDown Control - c#

I have some DomainUpDown controls in my winforms application. I cant find an option to set the default value for them on start up. Is there a way to do this?
At the moment, I have an enum type like this:
public enum ComparisonMode {Settings, Readings};
And I have set the SelectedItemChanged event of each DomainUpDown control to something like this:
private ComparisonMode ComparisonA; //enum to hold state of upDownA
private void upDownA_SelectedItemChanged(object sender, EventArgs e)
{
switch (upDownA.Text)
{
case "Settings":
ComparisonA = ComparisonMode.Settings;
break;
case "Readings":
ComparisonA = ComparisonMode.Readings;
break;
}
}
When I start the application, all the domainupdown controls have nothing selected, so user must set each of them to either Settings or Readings befor starting to work with the application.
How can I set for all of them a default value of for example (Readings)? I am thinking of looping over the controls (As they are inside a TableLayoutPanel).
I came up with this idea so far, It seems to work:
foreach (TableLayoutPanel tlp in tableCriterias.Controls)
{
foreach (Control ctrl in tlp.Controls)
{
var dud = ctrl as DomainUpDown;
if (dud != null)
{
dud.DownButton(); dud.DownButton();
//Going down 2 times to select default value
}
}
}
I do the above loop in the Load event of my form, but it makes everything very slow in the beggining since I have like 100 of these UpDown Controls.

No need to do this, you can set the SelectedIndex like this :
DomainUpDown dd = new DomainUpDown();
dd.Items.Add("settings");
dd.Items.Add("Reading");
dd.SelectedIndex = 0; // this will make sure you get the first item selected

Related

C# Window From Autoselects Text

I have not dealt with WinForms for a long time.
Now I'm stuck with something trivial but cannot figure it out.
I have a Winform and when a Timer Tick happens I want to show a message in a new form message box:
frmMessage frmM = new frmMessage();
frmM.txtMessage.Text = ConfigurationSettings.AppSettings["Message"];
frmM.Show();
It works but the text in the textbox shows as selected(with a blue background).
I tried
txtMessage.SelectionLength = 0;
Did not help.
Also tried to set focus to a different control, did not help either.
for now, as a workaround, I will use a Label.
This is a consequence of the way TextBox Class is implemented. If a selection is not specifically set, all text will be selected when the control gets focus.
From TextBox.OnGotFocus:
Protected override void OnGotFocus(EventArgs e) {
base.OnGotFocus(e);
If (!selectionSet) {
// We get one shot at selecting when we first get focus. If we don't
// do it, we still want to act Like the selection was set.
selectionSet = true;
// If the user didn't provide a selection, force one in.
If (SelectionLength == 0 && Control.MouseButtons == MouseButtons.None) {
SelectAll();
}
}
Additionally due to the way the SelectionLength Property is implemented, setting that property to zero does not set the selectionSet` flag as it is already zero.
Instead, set the TextBox.SelectionStart Property immediately after setting the text as this will set that flag.
txtMessage.SelectionStart = 0;
However, your work-a-round of using a Label to display a message is much more appropriate than using an input control.
This is not the best answer but it works. You can try this
frmMessage frmM = new frmMessage();
frmM.txtMessage.Text = "";
frmM.txtMessage.AppendText(ConfigurationSettings.AppSettings["Message"]);
frmM.Show();

Responsive Design UI with DockPanel Suite

I have design 1 winform to look like the picture. But I want the highlighted yellow part to be dockable with dockpanel suite reference. Is that do-able or any other suggestion of better design?
Right now the treeview is on the dockpanel and the red box part is a usercontrol placed in the same dockpanel. I tried to put the redbox as another form but I can't place it as it is in the picture. Also, this winform is need to be responsive so I put in the redbox part in a table layout panel.winform design and not familiar actually with the dockpanel suite reference. If there is a beginner tutorial that I can refer to, it would be much appreciated.
Current design:
There are two approach to your problem. First is dirty one and second elegant one. By dirty and elegant i mean way they display. Method they work are both same.
I will explain to you how to do it on empty form and you just implement that in your populated one.
First create new form.
Add 2 or more GroupBoxes to it
Add some items inside them (just to see if it works)
At the top of the each boxes add Button which will toggle visibility
Our form now looks like this and let's look of code behind it.
using System;
using System.Drawing;
using System.Windows.Forms;
namespace Test
{
public partial class TestForm : Form
{
// This is property
bool ShowFirstGroupBox
{
get
{
// We let user get our property from private variable
return _ShowFirstGroupBox;
}
set
{
// When user change this property we do something based on that
switch(value)
{
case true:
groupBox1.Size = new Size(groupBox1.Width, FirstGroupBoxDefaultHeight);
break;
case false:
groupBox1.Size = new Size(groupBox1.Width, 55);
break;
}
_ShowFirstGroupBox = value;
}
}
bool ShowSecondGroupBox
{
get
{
return _ShowSecondGroupBox;
}
set
{
switch (value)
{
case true:
groupBox2.Size = new Size(groupBox1.Width, FirstGroupBoxDefaultHeight);
break;
case false:
groupBox2.Size = new Size(groupBox1.Width, 55);
break;
}
_ShowSecondGroupBox = value;
}
}
// We store our boxes current state ( TRUE = shown, FALSE = HIDDEN )
bool _ShowFirstGroupBox = true;
bool _ShowSecondGroupBox = true;
// We store our default height for groupboxes
int FirstGroupBoxDefaultHeight;
int SecondGroupBoxDefaultHeight;
public TestForm()
{
InitializeComponent();
// Assigning default height of our groupboxes
FirstGroupBoxDefaultHeight = groupBox1.Height;
SecondGroupBoxDefaultHeight = groupBox2.Height;
}
private void button1_Click_1(object sender, EventArgs e)
{
ShowFirstGroupBox = !(_ShowFirstGroupBox); // This sets our property value to opposite of this boolean
}
private void button1_Click_1(object sender, EventArgs e)
{
ShowSecondGroupBox = !(_ShowSecondGroupBox); // This sets our property value to opposite of this boolean
}
}
}
Now when we have code like this and press button it will collapse groupbox.
NOTE: Controls under groupbox are still on place but just hidden since they are child of groupbox and everything outside of bounds is not visible to user.
This is dirty way since i would like to display it much prettier with MINUS sign on the right side of the groupbox title so i do not have button inside it. To do this you would need to create custom control which inherits groupbox, add button to it and position it in title bar and create event for it. It is easy if you have ever tried creating custom controls but if you haven't and you think dirty approach is okay with you then do not try it.

C# All Check-box Appearance

In my WinForms Visual Studio application i have a checkbox styled as a Flat Button with this C# code:
private void checkBox1_CheckedChanged(object sender, EventArgs e)
{
if (TestBox.Checked == true)
{
TestBox.Image = Image.FromFile("M:\\CheckBox_52x.png");
TestBox.ImageAlign = ContentAlignment.MiddleCenter;
TestBox.FlatAppearance.BorderSize = 0;
// make all four (!) BackColors transparent!
TestBox.BackColor = System.Drawing.Color.Transparent;
TestBox.FlatAppearance.CheckedBackColor = Color.Transparent;
TestBox.FlatAppearance.MouseDownBackColor = Color.Transparent;
}
else
{
TestBox.Image = Image.FromFile("M:\\CheckBoxUncheck_52x.png");
TestBox.ImageAlign = ContentAlignment.MiddleCenter;
TestBox.FlatAppearance.BorderSize = 0;
// make all four (!) BackColors transparent!
TestBox.BackColor = System.Drawing.Color.Cyan;
TestBox.FlatAppearance.CheckedBackColor = Color.Cyan;
TestBox.FlatAppearance.MouseDownBackColor = Color.Cyan;
}
}
I was wondering, if instead of doing this to every single checkbox in my application, can i make the "UNCHECKED" version i have coded the default checkbox style for this applicatiom - eg - every time i create a new one it appears with these properties.
Please keep in mind that i am brand new to coding in C#.
If you want multiple controls to use the same eventhandler, that's easy - just use the same event handler. Change your code to something like:
private void HandleCheckBoxCheckedChanged(object sender, EventArgs e)
{
CheckBox checkBox = (CheckBox) sender;
string imageFile;
Color color;
if (checkBox.Checked == true)
{
// TODO: Use resources embedded within your app
imageFile = "M:\\CheckBox_52x.png";
color = Color.Transparent;
}
else
{
imageFile = "M:\\CheckBoxUncheck_52x.png";
color = Color.Cyan;
}
// TODO: Load each file once and reuse the bitmap, I suspect.
checkBox.Image = Image.FromFile(imageFile);
checkBox.ImageAlign = ContentAlignment.MiddleCenter;
checkBox.FlatAppearance.BorderSize = 0;
checkBox.BackColor = color;
checkBox.FlatAppearance.CheckedBackColor = color;
checkBox.FlatAppearance.MouseDownBackColor = color;
}
You can then attach the same handler to all your checkboxes.
If you have multiple classes, you could make that a public static method. At that point you may need to add the event handler in code rather than getting the designer to do it - I don't know whether the designer knows how to use static methods for event handlers. But it would just be something like:
TestBox.CheckedChanged += CheckBoxUtilities.HandleCheckBoxCheckedChanged;
That's if you really just want the same code to be used for event handlers. Other things to consider are:
Constructing a subclass of CheckBox as suggested by rakatherock. My own experience with creating custom controls in Windows Forms has not been great, but from an OO perspective it feels fine. An initial implementation could just derive from CheckBox and implicitly add an event handler which does exactly what your current code does.
If you want to find all the CheckBox controls in a form at some point, you can use the Controls property and then recurse through any control which itself a container. I won't go into the details of that now though, as it sounds like you don't really want this - unless you did it just to find all the CheckBox controls and add the same event handler to all of them.
This can be done by creating custom checkbox control.
From the question what you are trying to do is to manipulate all check boxes in the application from a single check box so here the logic goes like:
Save the All checkbox value(Checked or unchecked) in the settings
To create a settings value
Right Click Project>Properties>Settings>Give Name as someBoolValue,type as bool,Scope as User
So on CheckChanged event of this check box save the value in Settings variable that we have created just now.In CheckChangedEvent of main All Check box code goes like:
Properties.Settings.Default.someBoolValue=cbCheckBox.Checked;
Properties.Settings.Default.Save();
Now on every form load are where ever the event is suitable do like
foreach(Control c in this.Controls)
{
if(c is CheckBox)
{
c.Checked=Properties.Settings.Default.someBoolValue
}
}
Note:You can replace all the check box that i implemented with your custom controls.I have given you just an idea how to do it.

C# Dynamic form (reflection) - linking controls

Sorry for the poor quality of the title. I couldn't think of a better way to phrase this.
For a project I'm currently working on with a few friends, I got myself in the situation where I have created a dynamic form (with reflection) which I now want to validate.
Example (ignore the black box, it contains old form elements which are now irrelevant and i didn't want to confuse you guys):
As you may have guessed already, it is an application for creating a mysql database.
Which is where I get to my problem(s). I want to disable checkboxes if others are checked.
For example: If I check "PrimaryKey" I want to disable the checkbox "Null".
Changing from unsigned to signed changes the numericupdown minimum and maximum etc.
But with reflection and all, I find it difficult to know exactly which checkbox to disable.
I was hoping you guys would have some suggestions.
I have been thinking about this for a while and a few thoughts have come to mind. Maybe these are better solutions than the current one.
Thought 1: I create UserControls for every datatype. Pro's: no problems with reflection and easy identifying of every control in the UserControl for validation. Con's: Copy-Pasting, Lots of UserControls, with a lot of the same controls.
Thought 2: Doing something with the description tags for every property of the classes. Creating rules in the description that allow me to link the checkboxes together. Here I'll only have to copy the rules to every class property and then it should be ok.
I had been thinking of other solutions but I failed to remember them.
I hope you guys can give me a few good pointers/suggestions.
[Edit]
Maybe my code can explain a bit more.
My code:
PropertyInfo[] properties = DataTypes.DataTypes.GetTypeFromString(modelElement.DataType.ToString()).GetType().GetProperties();
foreach (PropertyInfo prop in properties)
{
if (prop.Name != "Label" && prop.Name != "Project" && prop.Name != "Panel")
{
var value = prop.GetValue(modelElement.DataType, null);
if (value != null)
{
tableLayoutPanel1.Controls.Add(new Label { Text = prop.Name, Anchor = AnchorStyles.Left, AutoSize = true });
switch (value.GetType().ToString())
{
case "System.Int32":
NumericUpDown numericUpDown = new NumericUpDown();
numericUpDown.Text = value.ToString();
numericUpDown.Dock = DockStyle.None;
tableLayoutPanel1.Controls.Add(numericUpDown);
break;
case "System.Boolean":
CheckBox checkBox = new CheckBox();
checkBox.Dock = DockStyle.None;
// checkbox will become huge if not for these changes
checkBox.AutoSize = false;
checkBox.Size = new Size(16, 16);
if (value.Equals(true))
{
checkBox.CheckState = CheckState.Checked;
}
tableLayoutPanel1.Controls.Add(checkBox);
break;
default:
MessageBox.Show(#"The following type has not been implemented yet: " + value.GetType());
break;
}
}
}
}
Here is a mockup from my comments:
// The ViewModel is responsible for handling the actual visual layout of the form.
public class ViewModel {
// Fire this when your ViewModel changes
public event EventHandler WindowUpdated;
public Boolean IsIsNullCheckBoxVisible { get; private set; }
// This method would contain the actual logic for handling window changes.
public void CalculateFormLayout() {
Boolean someLogic = true;
// If the logic is true, set the isNullCheckbox to true
if (someLogic) {
IsIsNullCheckBoxVisible = true;
}
// Inform the UI to update
UpdateVisual();
}
// This fires the 'WindowUpdated' event.
public void UpdateVisual() {
if (WindowUpdated != null) {
WindowUpdated(this, new EventArgs());
}
}
}
public class TheUI : Form {
// Attach to the viewModel;
ViewModel myViewModel = new ViewModel();
CheckBox isNullCheckBox = new CheckBox();
public TheUI() {
this.myViewModel.WindowUpdated += myViewModel_WindowUpdated;
}
void myViewModel_WindowUpdated(object sender, EventArgs e) {
// Update the view here.
// Notie that all we do in the UI is to update the visual based on the
// results from the ViewModel;
this.isNullCheckBox.Visible = myViewModel.IsIsNullCheckBoxVisible;
}
}
The basic idea here is that you ensure that the UI does as little as possible. It's role should just be to update. Update what? That's for the ViewModel class to decide. We perform all of the updating logic in the ViewModel class, and then when the updating computations are done, we call the UpdateVisual() event, which tells the UI that it needs to represent itself. When the WindowUpdated Event occurs, the UI just responds by displaying the configuration set up by the ViewModel.
This may seem like a lot of work to set up initially, but once in place it will save you tons and tons of time down the road. Let me know if you have any questions.
Try relating the event of one checkbox to disable the other; something like this:
private void primaryKeyBox_AfterCheck(object sender, EventArgs e)
{
nullBox.Enabled = false;
}
This is a very simple example and would have to be changed a bit, but for what I think you're asking it should work. You would also have to add to an event for the boxes being unchecked. You would also need logic to only get data from certain checkboxes based on the ones that are and are not checked.
For all the other things, such as changing the numbers based on the dropdown, change them based on events as well.
For WinForms I would use data binding.
Create an object and implement INotifyPropertyChanged and work with that object.
Then, If you have an object instance aObj:
To bind the last name property to a textbox on the form do this:
Private WithEvents txtLastNameBinding As Binding
txtLastNameBinding = New Binding("Text", aObj, "LastName", True, DataSourceUpdateMode.OnValidation, "")
txtLastName.DataBindings.Add(txtLastNameBinding)
Take a look here for more info.
INotifyPropertyChanged

Jumping to next tab

I have a tab control in my WPF application with multiple tabs. Each tab gives access to several buttons, text boxes, drop downs. Now before moving to the next tab valid entries in each of the controls in the tab is to be checked or jumping to the next tab should not be allowed. How can this be done?
I was able to use IsEnable property to do this. But I want it like, when I click on the next tab it should, without entering the next tab, display a warning that such and such entry in the present tab is not valid.
If you adhere to the Selected event you can do something like this:
// Keep a global variable for the previous index
int prevIndex = 0;
private void tabControl_Selected(object sender, TabControlEventArgs e)
{
TabControl tc = sender as TabControl;
if (tc != null)
{
bool letSwitchHappen = validateTabControls(tc.SelectedIndex);
if (!letSwitchHappen)
{
tc.SelectedIndex = prevIndex;
}
prevIndex = tc.SelectedIndex;
}
}
Where validateTabControls is something like:
private bool validateTabControls(int tabIndex)
{
bool validEntries = false;
// Some code here to set validEntries according to the control at tabIndex
return validEntries;
}
Take a look at this example from Josh Smith.
It shows explicitly how to do this, and Josh is well-known (and respected) in the WPF world.

Categories