Adding controls to User Controls dynamically - c#

I want to add a control to a user control in an event handler (like a button click event).
I'm trying to add a datagridview lookup control dynamically, but I couldn't get that to work, so I tried just adding a button with this code:
private void btnCreateNewButton_Click(object sender, EventArgs e)
{
Button btn = new Button();
btn.Location = new Point(100, 640);
btn.Size = new Size(100, 30);
btn.Text = "Click Me";
btn.Click += (s, ea) => MessageBox.Show("New button clicked");
this.Controls.Add(btn);
}
When i click my Create New Button, no button appears.
If I add the exact same code into a form instead of a usercontrol, the button is created and displays as intended, but in a user control nothing happens.
In the user control I've also tried
this.Parent.Controls.Add(btn) and
this.ParentForm.Controls.Add(btn)
but to no avail.
Anybody got any ideas?
Thanks,
Ciaran.

You place your button on 100,640 point. Please ensure that your user control can accomodate your dynamic button. Otherwise, you won't see it.
I used your code and it worked fine for me, just ensure the proper size of both parent form and user control.

Most likely it is just that your button is being placed out of the bounds of the parent control and/or behind another control. I don't believe that UserControls or Forms are special in respect to adding controls at run-time, but a simple difference may be that Forms are by default re-sizable whereas UserControls aren't? Either way I don't think either Control type will automatically resize to fit all their child controls, so it's quite easy to put a new/dynamic control in the wrong place and have it not be visible.

Related

C# Click event for multiple controls inside custom control

I'm trying to make a custom User Control with multiple controls inside (for this example, a Picture box and a label) and I want them all to respond to the same event that I make on the form where I'm using it, all th objects would be:
UserControl1
pictureBox1
label1
However, when i make the (click) event on the form where I wanna use (Form1) the event only applies to the background (userCoontrol1), and therefore it will not work if I click the Picturebox or label, how could I make it that the event applies to every control inside?
I have tried making a click event for userControl1 and applying the same to the others and that works, but I need to change the behavior from the parent which is why this doesn't work, and I'm not sure how I can override this.
Taking into account your comment... One method might be the following
link click event of usercontrol to form1, in form1 code. lets say your function in form1 is called myButton_Click.
UserControl1.Click += new System.EventHandler(myButton_Click);
Then within UserControl1, create an on-click event (lets say "Control_Click") that simply invokes the UserControl1.Click eventhandler.
private void Control_Click(object sender, EventArgs e)
{
Click?.Invoke(this, new EventArgs());
}
Finally link each control's click in usercontrol to that Control_Click event within the usercontrol's constructor
picturebox1.Click += new System.EventHandler(Control_Click);
label1.Click += new System.EventHandler(Control_Click);

How to access the txt info inside a ToolTip from a programmatically created button?

I have problems to access the string inside a programmatically created button. Have a program which reads from a database and shows in a visual form, with buttons, the info of a specific process. Afterwards I want to make available this info with a "click" and show it in a window of the Form.
I create the button (boton1) programmatically, reading registers in a database (the number of buttons created depends of the registers and their values), and in the same step I create a new nutton I create their Tooltip (Tooltip1). So at the end I have a grid of buttons where I can see their tooltips if I haver the mouse over them. What I need is to be able to press these buttons and show in a textbox the info of these specific button's tooltip. The problem is because the boton1 creation is inside a method which creates the grid it's not accesible (I think this is the reason) from a method_click so the button (boton1) or Tooltip1 doesn't exists inside the button_click event, and if I create them it doesn't show when I click the Tooltip1 info but an empty string...
This is my code with the empty string, it doesn't show the info I see in the tooltips but "..." when I "click" on them.
protected void boton1_Click(object sender, EventArgs e)
{
ToolTip Tooltip1 = new ToolTip();
//This Tooltip is already created in other part of the code but without the code "running" don't exist for the button event creation
Button boton1 = sender as Button;
//Same here, already working and the tooltips seems fine but don't exist in the button_click event
//identify which button was clicked and perform necessary actions
String txtTool = tool.GetToolTip(button);
String info = Tooltip1.GetToolTip(boton1);
}

Duplication Controls Winforms

I have such a situation here.
Let's say we have three button on our Form, and one Control, which is Panel, and which is hidden when the Form is loaded. Here is it
When I click on Button 1, that Panel have to be shown under Button1, when clicking on Button2, it have to be showned under Button2 and so on. Let's say I clicked on Button2.
Now I want that same Panel to show, when Clicking on Button1 and not at the same place. I need the same panel to be showed under buttons when clicking them.For example, the same panel is showing when clicking button 3
I made this only working for only one button. I can't have 2 controls with same attributes, but I need somehow to duplicate that control.I And I think it have to be done with UserControl.
private void btn_click(Control sender, EventArgs e)
{
var btn = sender as Button;
panel1.Left = btn.Left;
}
now assign this even handler to click event for all buttons.
The var btn.... line will represent the button that was clicked, or the control that triggered the event, so from there you can set the panel's location.

User Control with button and button events

I am currently working on my first User Control, and are now experiencing some minor problems.
The control is a custom PictureBox with a Button to clear the picture. I am overriding the OnPaint(PaintEventArgs e) method and invalidating the control on MouseEnter and MouseLeave to draw new borders to the control based on mouse state.
This all work as it should. The problem occurs when I want to add a button in the upper right corner (relative to the PictureBox).
1.
The button will not have the correct location relative to the PictureBox. It is placed at the 0th Y-coordinate which is fine, but the X-coordinate is only at position 100, where it should be 160. I am using the User Controls Width property when placing the button, but it seems as it is getting a default value of 100 instead of the 160 that is assigned creating the PictureBox on the form.
CustomPictureBox cpic = new CustomPictureBox();
cpic.Location = new Point(20, 20);
cpic.Height = 80;
cpic.Width = 160;
this.Controls.Add(cpic);
And the button is added like this:
btnClear = new Button();
btnClear.Width = 20;
btnClear.Height = 20;
btnClear.Location = new Point(this.Width - btnClear.Width, 0);
btnClear.Text = "X";
this.Controls.Add(btnClear);
Where does this DefaultValue come from and how can it prevent the control from using it and instead following the width that is specified when initializing a new instance of the control?
2.
Another thing is that I can not get the events for the button to work. I have been googling a lot and tried everything that I can possibly think of, but the events are still not fireing :(
It must be possible to hook on to the buttons MouseClick, MouseEnter and MouseLeave events directly from the User Control?
If you want to see the complete code, you can find it here:
http://pastebin.com/vL14Q5CX
Thanks!
The button is not aligning as expected because:
The button's location is being set in the constructor of the user control
The user control's width is then set in the form
The user control's Resize event is not being handled
In your user control wire up the Resize event and update the location of the button, i.e.:
private void CustomPictureBox1_Resize(object sender, EventArgs e)
{
btnClear.Location = new Point(this.Width - btnClear.Width, 0);
}
The reason the button click events aren't working is because they only bubble up to the parent user control; they will not be received by the form that is hosting the control. You need to create a new custom event handler on your user control that you fire from within the button click event of your user control. You then handle that custom event handler on your form.
HTH

Customizing a TabControl for the Closing of Individual Tabs

My scenario is the following:
I am working on a winforms application in C# that has a button inside the main page of a tabcontrol that will generate another tabpage each time that it is clicked. Each new tabpage will contain a layout defined by a user control.
My Questions are:
How can I allow the user to then close one of the tabs that were created dynamically at runtime?
How might I go about modifying the tabcontrol itself so that it has a small 'X' in each tab that the user may click on in order to close that particular tab? (Like Firefox has)
How can I expose the SelectedIndex property of the tabcontrol to the user control if I want to close the tab with a button inside the user control instead?
I found this code and was very helpful to me:
private void tabControl_MouseUp(object sender, MouseEventArgs e)
{
// check if the right mouse button was pressed
if(e.Button == MouseButtons.Right)
{
// iterate through all the tab pages
for(int i = 0; i < tabControl1.TabCount; i++)
{
// get their rectangle area and check if it contains the mouse cursor
Rectangle r = tabControl1.GetTabRect(i);
if (r.Contains(e.Location))
{
// show the context menu here
System.Diagnostics.Debug.WriteLine("TabPressed: " + i);
}
}
}
}
TabControl: How To Capture Mouse Right-Click On Tab
I created a derived tab control about one year ago. I am not going to post the source here, because it's about 700 lines long and coded quite messy. Maybe I will find some time to clean the code up and then release it here. For now I will briefly outline the way it is build.
Each tab page has a 'X' icon to the left of the title and the tab pages support reordering by drag and drop and moving them between multiple tab control.
I choose the easy way to get the icon on the tab pages. The tab control has the TabControl.ImageList property and a tab page has a TabPage.ImageIndex property. So I just added three icons to a image list - normal, hover, pressed - and process the mouse events.
With TabControl.GetTabRect() you can test if the mouse is over a specific tab pages and with some math you find if it is over the icon. Then you just need to change the icon depending on the mouse button state and eventually remove the tab page under the mouse if the button was pressed.
The main problem with this solution is, that calculating if the mouse is over the icon requires to know where the icon is painted relative to the tab page and this might change with a new windows version. And the icon is to the left of the title, but that does not look too bad.
I did the following:
on the create (add) TabPage stage, I added a toolStrip
ToolStrip ts = new ToolStrip();
ts.Dock = DockStyle.Top;
ts.RightToLeft = System.Windows.Forms.RightToLeft.Yes;
Then, create the X button and add it to toolstrip
ToolStripButton ToolStripButton = new ToolStripButton("X");
ts.Items.Add(ToolStripButton);
create an event on clicking the X button
ToolStripButton.Click += new EventHandler(ToolStripButton_Click);
add toolstrip to the tabpage
tabControl1.TabPages[curenttabpage].Controls.Add(ts);
now for the ToolStripButton_Click is as follows:
void ToolStripButton_Click(object sender, EventArgs e)
{
ToolStripButton t = (ToolStripButton)(sender);
ToolStrip ts = t.Owner;
TabPage tb = (TabPage)
(ts.Parent);tabControl1.TabPages.Remove(tb);
}
Maybe it is not as you want, but it will work well.
I created a setup that is similar.
Each control that is added to the tab page at runtime is derived from a special base control I created. This base control has a close button (along with some other features such as safe to close flag).
Close tab code I'm using on my base control:
TabPage tabpage = (TabPage)this.Parent;
TabControl tabControl = (TabControl)tabpage.Parent;
tabControl.TabPages.Remove(parent);
I know this is an old thread but I did find this link that will allow you to "hide" tabs in an array and then you can just re-load the tabs you want at run time. I added this more for a place I can easily find it again.
This code might help throgh closing the tab controls with middle mouse click :
private void tabControl1_MouseDown(object sender, MouseEventArgs e)
{
if (e.Button != System.Windows.Forms.MouseButtons.Middle)
return;
for (int i = 0; i < MainTabControl.TabPages.Count; i++)
{
if (this.MainTabControl.GetTabRect(i).Contains(e.Location))
{
this.MainTabControl.TabPages.RemoveAt(i);
return;
}
}
}
It´s works!
TabPage tabpage = (TabPage)this.Parent;
TabControl tabControl = (TabControl)tabpage.Parent;
tabControl.TabPages.Remove(tabpage);

Categories