User Control Form Click event not clicking on label C# - c#

I have a problem with User form Click that I am trying to make in C# using a usercontrol.
It consists of a picturebox and a label. I want to call the click event but the picturebox and the label don't do anything when I click them. Only the background area of the usercontrol does what I want it to do. Any ideas?
here's my code
for (int i = 0; i < listitems2.Length; i++)
{
listitems2[i] = new declined();
//adding sample data to each dynamic user
listitems2[i].dicon = dicon[i];
listitems2[i].did = did[i];
listitems2[i].dname = dname[i];
//adding data to flow layout panel
flowLayoutPanel2.Controls.Add(listitems2[i]);
// below line will assing this (usercontrolclick) event to every user control created dynamically
listitems2[i].Click += new System.EventHandler(this.UserControl_Click);
}
for click function
void UserControl_Click(object sender, EventArgs e)
{
string ctrlName = ((UserControl)sender).Name;
applicable obj = (applicable)sender;
studid.Text = obj.id;
studname.Text = obj.name;
pictureBox1.Image = obj.icon;
}

You added OnClick handler to your UserControl, so only clicks made on UserControl will be registered. To enable Click event for all the controls on your form, you need to add your click handler to all other controls.
But, according to your code, you're adding click handling on form where your control is located. In this case, you cannot register clicks on control from "outside" (you can by making Label and PictureBox controls public and adding handlers for their OnClick events but that is wrong way to do it)
My suggestion is to make custom event on your form and raise it on Form, Label and PictureBox click, and then make handler for that event on form which holds your UserControl.
Something like this:
//make custom eventHandler on your UserControl
[Browsable(true)]
public event EventHandler UserControlClicked;
//constructor
public UserControl1()
{
InitializeComponent();
//after intialize compoment add same handler for all three controls
this.Click += ControlClicked;
this.pictureBox1.Click += ControlClicked;
this.label1.Click += ControlClicked;
}
//this method will "catch" all clicks
private void ControlClicked(object sender, EventArgs e)
{
//raise event
UserControlClicked?.Invoke(this, e);
}
and on form where your custom control is, add handler for UserControlClicked (maybe with cast, I don't know what listItems2[i] contains):
listitems2[i].UserControlClicked+= new System.EventHandler(this.UserControl_Click);
or maybe like this (with casting)
(listitems2[i] as UserControl1).UserControlClicked+= new System.EventHandler(this.UserControl_Click);
and handle the rest in your UserControl_Click method like before

Related

Windows Forms click event not fired when clicking on label?

I have Windows Form TestForm, and in my Form I have several labels that are only used to display some text.
I need to display a MessageBox.Show anytime the Form is clicked. So I have an event handler for the click, which looks like this:
private void TestForm_Click(object sender, EventArgs e)
{
MessageBox.Show("The form has been clicked");
}
Unfortunately, the click event doesn't fire when I click over a label in the Form. Is there a way to fix this, besides consuming the click event for the labels?
Thanks.
To use the same click event for all labels:
In the properties for each label, go to the Events (lightning bolt tab).
You will see (probably near the top) a label for Click, click the dropdown for this event, and you will be shown a list of handlers that you could use for that label.
Here's the Properties > Events > Click handler (bottom right):
Because all of your labels are of the same type, and produce the same EventArgs, you are able to use the same handler for all of them.
Then, when you are adding more Labels, just choose the event handler from the Click event dropdown:
Hope this helps!
To flesh out LarsTech's comment, I have used something like this in the past when I was having problems with labels overlapping each other and lack of true transparency in WinForms. What I did was make the labels invisible on the Form, then iterate through them in the Form's paint event, pull the information out of them and then use Graphics.DrawString to draw the text. That way you you will still be able see them in design mode.
This is a quick example of what I mean.
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void Form1_Paint(object sender, PaintEventArgs e)
{
foreach (var temp in this.Controls)
{
if (temp is Label) //Verify that control is a label
{
Label lbl =(Label)temp;
e.Graphics.DrawString(lbl.Text, lbl.Font, new SolidBrush(lbl.ForeColor), new Rectangle(lbl.Location, lbl.Size));
}
}
}
private void Form1_Click(object sender, EventArgs e)
{
MessageBox.Show("The Form has been clicked");
}
}

Accessing Child control event from parent level wpf

I have a user control named myControl. I have rendered another user control named dialog inside myControl as <uc:dialog x:Name="dialog"> .
I have a button named as myButton inside the dialog user control. I need to get the lostfocus event of myButton from the parent level .ie,myControl code behind.How can I get that? Which is the best way to do that?
var myButton= dialog.FindName("myButton") as Button;
if (myButton!= null)
{
myButton.LostFocus += myButton;
}
I tried like this. But it doesn't work.Why?
You could define such an Event in your UserControl.
Then just register for this event.
public event EventHandler ButtonLostFocusEvent;
private void Button_LostFocus(object sender, RoutedEventArgs e)
{
EventHandler testEvent = this.ButtonLostFocusEvent;
// Check for no subscribers
if (testEvent == null)
return;
testEvent(sender, e);
}

Adding events to Form designer file

I created a new Event in my user control (SearchControl) like this:
//Event which is triggered on double click or Enter
public event EditRecordEventHandler EditRecord;
public delegate void EditRecordEventHandler(object sender, EventArgs e);
//Supressing the events
private bool _raiseEvents = true;
private void OnEditRecord(System.EventArgs e)
{
if (_raiseEvents)
{
if (this.SearchResultGridView.FocusedRowHandle > -1)
{
if (EditRecord != null)
{
EditRecord(this, e);
}
}
}
}
Now this Event is called when user double click a row in a grid. So from the properties window I selected the MouseDoubleClick Event of the grid view and called the above created EditRecord event.
private void SearchResultListGridControl_MouseDoubleClick(object sender, MouseEventArgs e)
{
// Check whether the user clicked on a real and not a header row or group row
DevExpress.XtraGrid.Views.Grid.ViewInfo.GridHitInfo info = SearchResultGridView.CalcHitInfo(e.Location);
if (info.InRow && !SearchResultGridView.IsGroupRow(info.RowHandle))
{
OnEditRecord(e);
}
}
Now the issue I am facing is every time I double click a row in grid view it calls the SearchResultListGridControl_MouseDoubleClick() which then calls OnEditRecord(), however the value of EditRecord is everytime null.
To solve this I checked the designer file of the Main Control which has SearchControl and could not find the EditRecord Event entry in this. So I manually created it like this:
this.MySearchControl.EditRecord += new performis.BA.Merkmalsleisten.Search.SearchControl.EditRecordEventHandle(this.MySearchControl_EditRecord);
Now the things are working fine, but my question is why it did not create it automatically at the first place? And as far I know it is not recommendable to add anything manually to the designer file..is there any other way I can do it?
Thanks
When you create event it has to be used in the form designer similar to how you are using MouseDoubleClick for the Grid (so you need to find event in the Misc category, because you didn't define CategoryAttribute, double clicked there, etc).
If I understand it right you want to subscribe to event automatically, when form is created. You can do this in the control constructor (find parent form control.Parent or control.FindForm()) or perhaps in the special method, which you have to call from the form constructor, which in turn is basically similar to wiring event manually (which you did in the designer created file, but, instead, you can do in the form file, which is totally ok to edit) Up to you.
Sure.
A better practice would be to add your binding line:
this.MySearchControl.EditRecord += new performis.BA.Merkmalsleisten.Search.SearchControl.EditRecordEventHandle(this.MySearchControl_EditRecord);
To the form's constructor. something like:
public MyForm()
{
this.MySearchControl.EditRecord += new performis.BA.Merkmalsleisten.Search.SearchControl.EditRecordEventHandle(this.MySearchControl_EditRecord);
//The rest of your constructor.
}

Activated event in baseform doesn't trigger

enter code hereI've built a winform MDI application based on two baseforms, a listform with a grid (_ListForm) and a dataform to display the child data (_DataForm).
When I load an inherited dataform into the MDI, the activated event from the base-form (_DataForm) is triggered and some properties are automatically set. When I load an inherited listform (_ListForm) into the MDI, the activated event is not triggered.
My childform doesn't have an (overrided) activated event, there is no significant difference in the two forms, just one triggers the event, one doesn't.
I've added the eventhandler in code and/or with the designer : no
trigger
I've added a new activated event in the childform and called
base.onActivated(e) : no trigger
For now I moved some of the code into the textchanged event (which also occurs once), but why is this Activated-event not being triggered?
Can add tons of code-samples if needed, but not sure what to post.
EDIT: Forgot to mention, it's the same with the LoadEvent - doesn't trigger in any way.
EDIT: Sources as per request:
_BaseForm : font and general background (no events)
public partial class _BaseForm : Form
{
public _BaseForm()
{
InitializeComponent();
}
_ListForm : grid and buttons
public partial class _ListForm : _BaseForm
{
public _ListForm()
{
InitializeComponent();
this.Activated += new EventHandler(_ListForm_Activated);
this.DialogResult = System.Windows.Forms.DialogResult.Cancel;
this.grid1.UltraGrid.DisplayLayout.Bands[0].Columns.ClearUnbound();
this.grid1.UltraGrid.DisplayLayout.Override.AllowAddNew = Infragistics.Win.UltraWinGrid.AllowAddNew.No;
this.grid1.UltraGrid.DisplayLayout.Override.AllowDelete = Infragistics.Win.DefaultableBoolean.False;
this.grid1.UltraGrid.DisplayLayout.Override.AllowUpdate = Infragistics.Win.DefaultableBoolean.False;
this.grid1.UltraGrid.DisplayLayout.Override.CellClickAction = Infragistics.Win.UltraWinGrid.CellClickAction.RowSelect;
this.grid1.PopulateGridColumns += new FB.Windows.Controls.Grid.PopulateGridColumnsEventHandler(grid1_PopulateGridColumns);
this.grid1.UltraGrid.InitializeLayout += new Infragistics.Win.UltraWinGrid.InitializeLayoutEventHandler(UltraGrid_InitializeLayout);
this.grid1.RowSelected += new FB.Windows.Controls.Grid.RowSelectedEventHandler(grid1_RowSelected);
}
_ListForm event (either in designer or code from ctor):
this.Activated += new System.EventHandler(this._ListForm_Activated);
this.Load += new System.EventHandler(this._ListForm_Load);
The event itself:
private void _ListForm_Activated(object sender, EventArgs e)
{
if (AutoSearchOnOpen)
{
button1_Click(sender, e);
this.grid1.Focus();
this.ActiveControl = this.grid1;
}
else
{
this.textBox1.Focus();
this.ActiveControl = this.textBox1;
}
}
I know the Click inside the activated event will fire each time it's activated, but for now that doesn't matter: the main problem is: the whole event wont fire. Although the event in the _DataForm (also inherited from _BaseForm) is fired.
In this case the grid (3rd party control) overloads (hijacks) the activated and loaded events for the form and don't trigger the base event after the original event.

User control click event not working when clicking on text inside control?

I have a user control called GameButton that has a label inside it. When I add the user control to my form, and add a click event to it, its triggered when you click on the background of the custom button, but not the text in the label? How would I fix this without adding a bunch of click events inside the user controls code?
edit: UI framework: winforms
If I am understanding you properly, your GameButton usercontrol will fire the event when clicked on, but not when the label is clicked on -- and you want both. This is because the label (a control) is on top of the background. Therefore, you need to register your label with the click event as well. This can be done manually in the designer or programmatically for each control on the page.
If you want to do EVERY control in the UserControl, put this into the UserControl's OnLoad event and you can use the same click event for every control:
foreach (var c in this.Controls)
c.Click += new EventHandler(yourEvent_handler_click);
public void yourEvent_handler_click (object sender, EventArgs e){
//whatever you want your event handler to do
}
EDIT: The best way is to create the click event handler property in the user control. This way, every time you add/remove a click event to your user control, it adds/removes it to all the controls within the user control automatically.
public new event EventHandler Click {
add {
base.Click += value;
foreach (Control control in Controls) {
control.Click += value;
}
}
remove {
base.Click -= value;
foreach (Control control in Controls) {
control.Click -= value;
}
}
}
This is as per another post:
Hope this helps!
You can create a new method and assign all the controls to it
private void Control_Click(object sender, EventArgs e)
{
this.OnClick(e);
}
This will raise main control(or usercontrol) event.
Set the "enable" property of your labels "False, then mouse events will work in user control.
You can make the events in the controls of the User Control call the event of the User Control like that:
foreach (Control c in this.Controls)
{
c.Click += (sender, e) => { this.OnClick(e); };
c.MouseUp += (sender, e) => { this.OnMouseUp(e); };
c.MouseDown += (sender, e) => { this.OnMouseDown(e); };
c.MouseMove+= (sender, e) => { this.OnMouseMove(e); };
}
Just put it in the constructor. This way when an event is added to the User Control using polymorphism it will work
Here This control has 4 child control like 3 label and 1 picturebox.
so add this.onClick(e) in c# or Me.onClick(e) in vb.net on there on click event
like this
Private Sub rate_lab_Click(sender As Object, e As EventArgs) Handles rate_lab.Click
Me.OnClick(e)
End Sub
So wherever click inside user control the click event act as single event

Categories