.NET UserControl accept button best practice? - c#

I have a windows forms app where I have split different functionality into several user controls. I want each of these user controls to have an accept button.
Any best practices here?
My idèa is to detect which user control that has focus, and than set it in the parent Form.
Any other idèas?

The best practice is usually to only have one accept button for your form so that its behavior is consistent. It generally would be confusing for users if hitting return caused different actions depending on which section of the form had focus. However, if you have a specialized application or users have requested this feature then I think the solution you propose would work.

Jan Miksovsky has an excellent blog on UI design, and wrote an article about this very thing.
Most UI platforms allow a designer to
indicate which button in a dialog
should be the default button: the
button that will be pressed if the
user types the Enter key. The default
button is generally the button the
user is most likely to press next,
often a button like OK that closes the
dialog. In very high-traffic dialogs,
you may want to consider dynamically
changing the default button to save
keystrokes and help speed the user's
task.
The example he uses is the "Select Names" dialog in Microsoft Outlook, which changes the default button depending on what you are doing.

I assume each user button is its own instance on the individual user controls?
If so then you can trap the button events on the Parent form. If you expose the individual buttons through a property you can tie into their Click events. Like all controls they have a name property so you can have one method that is called on all button click events.
Below I have a partial sample code. I have two user controls that have one button each. The button on UC1 is named "btn1" and "btn2" for UC2. I call the exposed property "ButtonOK"
public partial class UserControl1 : UserControl
{
public UserControl1()
{
InitializeComponent();
}
public Button ButtonOK
{
get { return btn1; }
}
}
public partial class UserControl2 : UserControl
{
public UserControl2()
{
InitializeComponent();
}
public Button ButtonOK
{
get { return btn2; }
}
}
Now on the parent ("Form1") when it loads have a mthod that ties into the Click events of each button but it calls the same method. Inside the method I test for the "Name" property.
public Form1()
{
InitializeComponent();
}
void Form1_Load(object sender, EventArgs e)
{
RegisterButtonEvents();
}
void RegisterButtonEvents()
{
userControl11.ButtonOK.Click += new EventHandler(ButtonOK_Click);
userControl21.ButtonOK.Click += new EventHandler(ButtonOK_Click);
}
void ButtonOK_Click(object sender, EventArgs e)
{
Button btn = sender as Button;
if (btn != null)
{
if (btn.Name == "btn1")
{
Console.WriteLine(" ButtonOK from UserControl1 was pushed. The tag is " + btn.Tag.ToString());
}
else if (btn.Name == "btn2")
{
Console.WriteLine(" ButtonOK from UserControl2 was pushed. The tag is " + btn.Tag.ToString());
}
}
}
You can also user the "Tag" property of a control. This property can be very useful as it can reference objects.
You don't need to do exactly as shown but you can use any "Parent" form to get a reference to the UserControls, have them expose their Buttons, then you can do anything you want with properties and events from those Buttons (or any control for that matter).
Keep in mind that if you are tying into the click event on the user control also (in addition to the parent form), you will have to be mindful of the order in which it will enumerate through it list of delegates and execute code after the event is intiated.
Hope that helps.

I know this is an old post, but I think I figured it out.
Use the "Enter" event on each user control from the main form, such that when the user "enters" (focuses on) the user control, this.AcceptButton = myUserControlButton. You can also use the "Leave" event on each user control to set the accept button back to the default, if you have one.

I'm not sure if I understood your question correctly.
If you want to assign one event to several buttons:
For this you could for instance:
- Get the button name on the Button_Click event.
- Enumerate between names
- Iterate over the controls.
Example bellow:
"How to get the button name from the Button_Click event".
// First; dont forget to assign the "Button_Click" event to your Button(s).
private void Button_Click(object sender, EventArgs e)
{
// The line bellow assigns to "btn" variable the currently clicked button.
Button btn = (Button)sender;
// Then using a switch block; you can compare the button name and
// perform the action desired for the clicked button.
switch(btn.Name)
{
case "buttonName1": /* Do Something Here */ break;
case "buttonName2": /* Do Something Here */ break;
// etc
}
}
Additionally; if you require; there's always the way to retrieve the Button outside the form class by exposing them.

Related

binding custom control to an external button

I have a custom control that i'm using in an external application. I want to bind a click event of a random button in the application to add data to my control.
Is something like that even possible?? Basically what i was thinking was creating a property in my control that allows a developer to add a button control to it at design time. And then when the application is run, any clicks registered on the button will be forwarded to a method in the custom control to add data.
Is this doable? if so, can someone explain what needs to be done exactly?
You can create a property of type Button in your custom control. Then when you put an instance of custom control on the designer, for that property, you will see a dropdown that shows all Button instances on the form which you can select one of them. It's enough to add a method to click event of the button in setter of the property:
using System;
using System.Windows.Forms;
public class MyControl : UserControl
{
private Button addButton;
public Button AddButton
{
get { return addButton; }
set
{
if (addButton != null)
addButton.Click -= new EventHandler(addButton_Click);
addButton = value;
if (addButton != null)
addButton.Click += new EventHandler(addButton_Click);
}
}
void addButton_Click(object sender, EventArgs e)
{
MessageBox.Show("Add Button Clicked!");
}
}
When you put it on designer, for AddButton property, a list o available buttons on the form will be shown. it's enough to choose one of them, then the behavior which you want (here in the example, showing the message box) will attach to click event of that button.

how to access a user define controls iner controls in parent form

I'm new to windows forms programming so my question may sound little strange.
I have created a user define control (countdown timer) now I'm creating n no of it dynamically in a form by Click of a button (Add new timer) its working well and good.
Here is the Creation Code
private void Addnew_Click(object sender, EventArgs e)
{
UserControl1.userControl11 = new UserControl1();
flowLayoutPanel1.Controls.Add(userControl11);
}
My user control has a Reset button that reset all the content inside the user define control.
it is also working, but What I want Allow user to reset all the Created timers using the “Reset All” button on the form.
Okay one way to do this.
Create a List<UserControl1> private member on your form called say _myUserControls
In your Addnew Handler add it to the list.
If you have a remove button, don't forget to remove from _myUserControls as well.
Add a Reset method to your UserControl1, that does what it needs to do.
Then in your Reset all button click handler
foreach(UserControl1 ctrl in _myUserControls)
{
ctrl.Reset();
}
Jobs a good 'un
The answer I referred you to in comments, would be a way of finding all instances of your UserControl1 class, so you wouldn't need an internal list.

Databound control won't lose focus [duplicate]

I have a Windows Forms Application. I have several forms in this application (a main form, and several specialized forms), and on only one form, click events are not firing for any of my buttons.
It is not that the code in the handler is broken. This can be determined by the fact that a breakpoint on the first line of the handler is never reached when clicking the button.
Other events are working (I'm using CheckedChanged events on this form and they are behaving).
My team members have reviewed, and also can't spot the problem.
Here is a simplified view of my code:
Designer Generated Code
partial class MyForm
{
private System.Windows.Forms.Button addButton;
private void InitalizeComponent()
{
this.addButton = new System.Windows.Forms.Button();
this.addButton.Name = "addButton";
// Drawing statements here
this.addButton.Click += new System.EventHandler(this.addButton_Click);
this.Controls.Add(this.addButton);
}
}
My Code
public partial class MyForm : Form
{
public MyForm()
{
InitializeComponent();
}
private void addButton_Click(object sender, EventArgs e)
{
MessageBox.Show("The debugger is not reaching a break point on this line");
}
}
Edit: Additional Information from Testing
There are several data-bound dropdownlists in my form. I have discovered that the click event only fails to fire if I make a selection in a drop down box first.
If I make no selections, the break point in the button's handler fires. Otherwise it doesn't. There are no events registered on these drop down lists.
Here is the reason:
When using data binding, when you enter a value in a data bound control, it first tries to validate entry and then if the entry was valid, data binding will put the value in data source, but if a validation error occurs validation returns false and your control goes to invalid mode.
When a child control of form didn't validate, by default you can not change focus from invalid control.
Click on a button by default causes validation of the control that are losing the focus, so you can't click on button, as you see your button reflect to mouse but not actually click.
The same problem will happen if you handle Validating event of a control like TextBox and set e.cancel = true.
Here is the fix:
you can fix this behavior using either of following options:
Set CausesValidation property of your button to false
Set AutoValidate property of your form to AutoValidate.EnableAllowFocusChange
This will do the trick for you
Change
public ScheduleMeeting()
{
InitializeComponent();
}
to
public MyForm()
{
InitializeComponent();
}
I have discovered the issue after further testing.
I the issue is not with button events, but with the form becoming blocked after making a selection from a drop down box.
I have not yet discovered why the form blocks after the drop down is selected (it has no events, but does have databinding, so there are some possible causes there).
Thank you for all your help!

Is there any way to detect a mouseclick outside a user control?

I'm creating a custom dropdown box, and I want to register when the mouse is clicked outside the dropdown box, in order to hide it. Is it possible to detect a click outside a control? or should I make some mechanism on the containing form and check for mouseclick when any dropdownbox is open?
So I finally understand that you only want it to close when the user clicks outside of it. In that case, the Leave event should work just fine... For some reason, I got the impression you wanted it to close whenever they moved the mouse outside of your custom dropdown. The Leave event is raised whenever your control loses the focus, and if the user clicks on something else, it will certainly lose focus as the thing they clicked on gains the focus.
The documentation also says that this event cascades up and down the control chain as necessary:
The Enter and Leave events are hierarchical and will cascade up and down the parent chain until the appropriate control is reached. For example, assume you have a Form with two GroupBox controls, and each GroupBox control has one TextBox control. When the caret is moved from one TextBox to the other, the Leave event is raised for the TextBox and GroupBox, and the Enter event is raised for the other GroupBox and TextBox.
Overriding your UserControl's OnLeave method is the best way to handle this:
protected override void OnLeave(EventArgs e)
{
// Call the base class
base.OnLeave(e);
// When this control loses the focus, close it
this.Hide();
}
And then for testing purposes, I created a form that shows the drop-down UserControl on command:
public partial class Form1 : Form
{
private UserControl1 customDropDown;
public Form1()
{
InitializeComponent();
// Create the user control
customDropDown = new UserControl1();
// Add it to the form's Controls collection
Controls.Add(customDropDown);
customDropDown.Hide();
}
private void button1_Click(object sender, EventArgs e)
{
// Display the user control
customDropDown.Show();
customDropDown.BringToFront(); // display in front of other controls
customDropDown.Select(); // make sure it gets the focus
}
}
Everything works perfectly with the above code, except for one thing: if the user clicks on a blank area of the form, the UserControl doesn't close. Hmm, why not? Well, because the form itself doesn't want the focus. Only controls can get the focus, and we didn't click on a control. And because nothing else stole the focus, the Leave event never got raised, meaning that the UserControl didn't know it was supposed to close itself.
If you need the UserControl to close itself when the user clicks on a blank area in the form, you need some special case handling for that. Since you say that you're only concerned about clicks, you can just handle the Click event for the form, and set the focus to a different control:
protected override void OnClick(EventArgs e)
{
// Call the base class
base.OnClick(e);
// See if our custom drop-down is visible
if (customDropDown.Visible)
{
// Set the focus to a different control on the form,
// which will force the drop-down to close
this.SelectNextControl(customDropDown, true, true, true, true);
}
}
Yes, this last part feels like a hack. The better solution, as others have mentioned, is to use the SetCapture function to instruct Windows to capture the mouse over your UserControl's window. The control's Capture property provides an even simpler way to do the same thing.
Technically, you'll need to p/invoke SetCapture() in order to receive click events that happen outside of your control.
But in your case, handling the Leave event, as #Martin suggests, should be sufficient.
EDIT: While looking for an usage example for SetCapture(), I came across the Control.Capture property, of which I was not aware. Using that property means you won't have to p/invoke anything, which is always a good thing in my book.
So, you'll have to set Capture to true when showing the dropdown, then determine if the mouse pointer lies inside the control in your click event handler and, if it doesn't, set Capture to false and close the dropdown.
UPDATE:
You can also use the Control.Focused property to determine if the control has got or lost focus when using a keyboard or mouse instead of using the Capture with the same example provided in the MSDN Capture page.
Handle the Form's MouseDown event, or override the Form's OnMouseDown
method:
enter code here
And then:
protected override void OnMouseDown(MouseEventArgs e)
{
if (!theListBox.Bounds.Contains(e.Location))
{
theListBox.Visible = false;
}
}
The Contains method old System.Drawing.Rectangle can be used to indicate if
a point is contained inside a rectangle. The Bounds property of a Control is
the outer Rectangle defined by the edges of the Control. The Location
property of the MouseEventArgs is the Point relative to the Control which
received the MouseDown event. The Bounds property of a Control in a Form is
relative to the Form.
You are probably looking for the leave event:
http://msdn.microsoft.com/en-us/library/system.windows.forms.control.leave.aspx
Leave occurs when the input focus leaves the control.
I just wanted to share this. It is probably not a good way of doing it that way, but looks like it works for drop down panel that closes on fake "MouseLeave", I tried to hide it on Panel MouseLeave but it does not work because moving from panel to button leaves the panel because the button is not the panel itself. Probably there is better way of doing this but I am sharing this because I used about 7 hours figuring out how to get it to work. Thanks to #FTheGodfather
But it works only if the mouse moves on the form. If there is a panel this will not work.
private void click_to_show_Panel_button_MouseDown(object sender, MouseEventArgs e)
{
item_panel1.Visible = true; //Menu Panel
}
private void Form1_MouseMove(object sender, MouseEventArgs e)
{
if (!item_panel1.Bounds.Contains(e.Location))
{
item_panel1.Visible = false; // Menu panel
}
}
I've done this myself, and this is how I did it.
When the drop down is opened, register a click event on the control's parent form:
this.Form.Click += new EventHandler(CloseDropDown);
But this only takes you half the way. You probably want your drop down to close also when the current window gets deactivated. The most reliable way of detecting this has for me been through a timer that checks which window is currently active:
[System.Runtime.InteropServices.DllImport("user32.dll")]
static extern IntPtr GetForegroundWindow();
and
var timer = new Timer();
timer.Interval = 100;
timer.Tick += (sender, args) =>
{
IntPtr f = GetForegroundWindow();
if (this.Form == null || f != this.Form.Handle)
{
CloseDropDown();
}
};
You should of course only let the timer run when the drop down is visible. Also, there's probably a few other events on the parent form you'd want to register when the drop down is opened:
this.Form.LocationChanged += new EventHandler(CloseDropDown);
this.Form.SizeChanged += new EventHandler(CloseDropDown);
Just don't forget to unregister all these events in the CloseDropDown method :)
EDIT:
I forgot, you should also register the Leave event on you control to see if another control gets activated/clicked:
this.Leave += new EventHandler(CloseDropDown);
I think I've got it now, this should cover all bases. Let me know if I'm missing something.
If you have Form, you can simply use Deactivate event just like this :
protected override void OnDeactivate(EventArgs e)
{
this.Dispose();
}

User Control Events and Overrides

I have a User Control for typical CRUD like actions on my WinForm app.
Validate, Insert, Update, Clear, Cancel, and Delete.
On every form I put this on I end up adding the click event, ucPersonNav.btnValidate.Click += new EventHandler(btnValidate_Click);, for every button.
What I am wondering is can I have the Events be on the User Control themselves and just have them point to a Method that I override on a Form by Form basis?
Something like this -->
namespace psUserControls
{
using System;
using DevExpress.XtraEditors;
public partial class ucVIUCCDwithWhoDoneIt : XtraUserControl
{
public ucVIUCCDwithWhoDoneIt()
{
InitializeComponent();
}
private void btnValidate_Click(object sender, EventArgs e)
{
ValidateEvent();
}
}
}
And then on a Form have this -->
void ValidateEvent()
{
if (dxValidDiagnosis.Validate())
{
if (planDiagnosisID != 0)
{
ucNavDiagnosis.btnUpdate.Enabled = true;
ucNavDiagnosis.btnDelete.Enabled = true;
}
ucNavDiagnosis.btnInsert.Enabled = true;
}
}
Is this feasible? Is it idiotic? If Yes then No then what steps do I need to take to make this work?
Thanks
i think .. not a bad idea..
but the approach would be very specific to your application.
we can have an enum for CRUD buttons - 6 enum items as you specified.
We can have a single event handler - delegate which takes above enum as a parameter.
Write an event (MyButtonClickedEvent) for this delegate which will be fired on each button clicked event.
on your control, on each button clicked event you can fire this event with respective enum item as a parameter.
e.g. on Validate button click, fire MyButtonClickedEvent with parameter as validate enum item.
On Inser button click, fire same MyButtonClickedEvent with parameter as Insert enum item.
This way you will have to handle single event on your form. You will be firing different events from your control. But this is to be done only once. On your form you will write a just one single handler - Method. In this method, you can differentiate depending on the enum type. .Net supports enum in switch-case construct. So you can easily identify the opteration that you have to perform.
All the users of your control will find it easier as they have to handle just one event. They will ignore the cases in switch construct which they are not interested.
Hope this helps.
You just need to define ValidateEvent as an event. In your UserControl:
public event EventHandler ValidateEvent;
On the form:
ucNavDiagnosis.ValidateEvent += new EventHandler(<name of event handler function>);
It's probably not a great idea to be accessing the buttons of the UserControl directly, however.

Categories

Resources