how to change text dynamically added button c# - c#

Add Buttons:
Button button = new Button();
this.Controls.Add(button);
button.Name = "btn" + id;
button.Text = "AAAA";
The result is the name of a button as btn55, but, how to change text on button name btn55?
something like
private void btnaktual_Click(object sender, EventArgs e)
{
btn55.Text = "BBB";
}
Gives me error:
Error 1 The name 'btn55' does not exist in the current context

Use this.Controls.Find("btn55",true).FirstOrDefault().Text = "BBB";

If you used the designer to put the button in the form, then a member variable would be created with the same name as the name of the form. As you create the button using code, there is no btn55 variable.
When you create the button you have a reference to it. You should just keep that reference so that you can use it later. Make a member variable in the form where you can store it, i.e. declare Button button; (or perhaps a more descriptive name) in the form class instead of inside the method where you create the button. Then you can use the variable later to access the button.

Your entire problem lies in the page load. When you click the button event the page posts back, so if you're control is not reloaded it no longer exists when the click event is called. Either you are not creating the button on postback or the button isn't in viewstate. Find Control will always return null until the button is created so most of these answers won't work for you yet.
These pages will help you:
http://forums.asp.net/t/1186195.aspx?FAQ+Why+do+dynamic+controls+disappear+on+postback+and+not+raise+events+
Dynamically Created Controls losing data after postback
http://www.codeproject.com/Articles/35360/ViewState-in-Dynamic-Control
Once you get that control reloaded, then you can get it from there pretty easily.

Try this:
var btn = Controls.Find("btn55") as Button;
btn.Text = BBB;

You need to search for the button in it's parent controller. Let's say you have a main form and the button placed in it. You can find using id of control in parent.
(MainForm.Controls.Find("btn"+number") as Button).Text= "BBB";

Related

C# WPF Create function that creats new inputs

I am using C# Wpf and i would like to create a function that once you click on a button A new Textbox will appear is this possible and I want to know if it possible to increase the form hight when a new Textbox is created
The question isnt exactly specific but yes you can make new UI elements in the code-behind. In WPF you would put your button on the window, then add the "Click" event to it. Then in the click event you could code something like. . .
private void Button_Click(object sender, RoutedEventArgs e)
{
Button newButton = new Button(); //Create a new button control and assign it to newButton
newButton.Width = 35; //Access fields like this (You can access any of the ones you access from the Xaml user interface)
newButton.Height = 20;
newButton.HorizontalAlignment = System.Windows.HorizontalAlignment.Left;
newButton.VerticalAlignment = System.Windows.VerticalAlignment.Top;
newButton.Content = "click me!";
grMain.Children.Add(newButton); //Add it to the grid
}
grMain is the name of my grid, make sure you name it and call it by the name. You can also call other elements, such as a stack panel or whatever you need. So for your case just make it a textbox instead of a button
Oops didnt see the second part of your question! To resize the window you need to first add a name to it in the XAML (Like you would name a grid or button - just name the window something). And just as we called grMain in my example call that and change the height/width properties.

How to reference dynamically created controls?

Is there a way to reference dynamically created controls, such as a couple TextBoxes and maybe a RadioButtonList when the user either click a button or changes the selected radio button.
I need to insert a record into a database but I need all of the values. I cannot hard-code the controls because they must be created on the fly.
TextBox t1 = new TextBox();
PlaceHolder1.Controls.Add(t1);
TextBox t2 = new TextBox();
PlaceHolder1.Controls.Add(t2);
RadioButtonList rbList = new RadioButtonList();
rbList.Items.Add(new ListItem("Today", "1"));
rbList.Items.Add(new ListItem("This Week", "2"));
rbList.SelectedIndexChanged += new EventHandler(rbList_SelectedIndexChanged);
PlaceHolder1.Controls.Add(rbList);
I need to reference the two textboxes and the RadioButtonList within rbList_SelectedIndexChanged or some other event. Adding EventHandlers to the textboxes do my no good because I need all three values to insert into the database.
My inital thought was to somehow pass reference of the texboxes to the rbList_SelectedIndexChanged event but I am unsure of how to do this and even more unsure if it will even work.
Any help would be appreciated.
I think you could accomplish this with FindControl(). You'll want to set an ID to those text boxes in the code behinds.
You probably have a reference to PlaceHolder1 within the rbList_SelectedIndexChanged event. So within the event:
var TextBox1 = (TextBox)Placeholder1.FindControl("{text box 1 ID here}");
var TextBox2 = (TextBox)Placeholder1.FindControl("{text box 2 ID here}");
Create a UserControl to encapsulate these controls. Put some logic inside to save both controls depending on their values. Add this user control to the PlaceHolder. View this article for further reading
My inital thought was to somehow pass reference of the texboxes to the bList_SelectedIndexChanged event
That's what I'd do. This is easily done by using an anonymous method for the event handler that can close over the needed variables:
rbList.SelectedIndexChanged += (s, e) =>selectionChangedHandler(rbList t1, t2);

Dynamically add a button - must be placed inside form tag

i am dynamically creating a button using C#. but i get an error when it get executed;
Control 'butidd' of type 'Button' must be placed inside a form tag with runat=server.
the code
Button but = new Button();
but.ID = "butidd";
but.Attributes.Add("runat", "server");
but.Text = "test";
but.Click += new EventHandler(but_click);
this.Controls.Add(but);
click event:
void but_click(object sender, EventArgs e){}
As the error clearly states, you need to add the control somewhere inside a <form runat="server">; not directly in the page.
If you want to add the control dynamically... Better create a panel in form design view and add the control dynamically to that panel...
If you create a panel on design view then it lays under the form tag...It is easiest one.... it avoids this type of confusions and errors...
try this link for reference... http://msdn.microsoft.com/en-us/library/kyt0fzt1.aspx

Dynamic Naming of C# Form Elements

My app needs to be able to dynamically create new form elements and work with them. Right now I have a panel with buttons and labels in it. I need to be able to make a duplicate of this and show it in my app and then work with it.
For example, I have panel1. Inside are label1, button1, and button2.
Label 1 just counts up by seconds.
When you click button1, label1 starts counting up. When you click button2, the timer stops.
My problem is that I need to be able to duplicate panel1 many times and still have the new buttons correspond to the correct labels.
On button_click
private void button1_Click(object sender, EventArgs e)
{
Button theSender = (Button)sender;
Panel parentPanel = (Panel)theSender.Parent;
}
From here, I can't target any of the child control . I'm used to targeting and handles in jQuery, so I don't even know the correct C# terminology for how to explain myself.
If understand your problem correctly, I recommend you to make a Usercontrol with a Panel and fill it with your Label, Button and whatever. Write the events for your buttons in the usercontrol. Then introduce this usercontrol in your form and it should work. You can introduce any number of usercontrols in your form and each button will behave/work for the label in that usercontrol only.
As you mentioned you are new in winforms and you are not sure what I am saying, let me know and I will help if I get enough time.
Hope it helps.
Children of a control can be accessed using Control.Contrtols collection, e.g. to access button on a form:
Button btn = this.Controls["button1"];
But that is only true if button1 is placed directly on your form and button1.Name property is set to "button1" (designer does that automattically, if you are creating your controls dynamically, you have to take care of naming your controls yourself.)
You can also enumerate child controls of any control, e.g. child controls of panel1:
foreach(Control c in panel1.Controls)
{
// do something, e.g.
if(c is Label){//do sth...}
if(c.Name.Equals("label1") && c is Label)
{
Label l = c as Label;
}
}
and as #rapsalands said, UserControl may be an answer for you.
I would create a user control (UserControl) for this.
Check this article for more explanation about the difference between Control and UserControl.
Controls and UserControls are easy to duplicate and the full functionality is there.
You can create new UI Controls in code as you would any other object: Button b = new Button();
Then you can add them to the form using form.Controls.Add(b). You'll need to position and size the controls as well (there are properties available for doing this) and hook up your event handlers using b.Clicked += form.button_click;.
To see an example of this, you can try having a look at the designer.cs file that is generated in Visual Studio (don't make changes to it, just have a look). It will look quite complex at first but might go some way to helping demystify Windows Forms, and you will be able to find all of the properties you need to set in there.
Whenever you update something in the designer, Visual Studio generates new code and puts it in the designer.cs file. The entire form is set up in the InitializeComponent() method, which is called from the constructor of your form. You should be able to copy some of that code and with a couple of modifications use it for creating your own dynamic UI elements.
As rapsalands says, it sounds like a user control would be useful in this situation, as it will help encapsulate the functionality you're after. However that may take a bit of time to get your head round and you may find it simpler for now to do everything in your form without creating a new control.
So you are a beginner and need some time to understand Usercontrol as I mentioned in my previous answer. Use a for loop in the Constructor or Load event of your form to dynamically generate controls.
Panel panel;
Label label;
Button button1;
Button button2;
for(int i = 0; i > count; i++)
{
panel = new Panel();
button1 = new Button();
button2 = new Button();
label = new Label();
panel.Controls.Add(button1);
panel.Controls.Add(button2);
panel.Controls.Add(label);
Controls.Add(panel);
button1.Click += Event1;
button2.Click += Event2;
}
private void Event1()
{
label.Text = "Button 1 Clicked."
}
private void Event2()
{
label.Text = "Button 2 Clicked."
}
This way certainly you can create as many controls you want and will also serve your purpose. Use some variables to locate the panel controls appropriately. Set any properties you wish to add in the for loop for the controls.
This is just an alternative for my previous answer. I still recommend the previous answer given by me. This code is dummy and not tested.
Hope it helps.

Dynamically add Button to Panel

I am adding a RadButton dynamically to a Panel. So I am creating the button as so:
RadButton btnAwesome = new RadButton();
btnAwesome.AutoPostBack = true;
btnAwesome.Text = "Click me...";
btnAwesome.ID = "LinkButtonTest";
btnAwesome.Click += new System.EventHandler(lnkbtnEditRecord_Click);
and it it should call this method onclick:
protected void lnkbtnEditRecord_Click(object sender, EventArgs e)
{
salesEditPanel.Visible = true;
resultPanel.Visible = false;
zipPanel.Visible = false;
ddlPanel.Visible = false;
topPanel.Visible = false;
}
It adds the button the Panel but it doesn't add the onclick to it. Any idea what I am missing?
Thanks!
You will need to run that code to initialize the button on every postback, and you will need to ensure that it's run sufficiently early in the page's lifecycle. Which page event is that code in, and will it be run on each successive postback?
The issue here is due to how postbacks work - Each time a page is requested (postback or not), the control instances are created. Once the controls are created and other page properties set, the viewstate is parsed to set the control's properties. Then events are created and dispatched.
The important thing here is, this instance of "page" is not the same instance that you generated before - it's a new one and the ASP.NET webforms engine has set all the properties for you as if it were the same. But on this instance, you haven't created your btnAwesome, so there's nothing there to send a "click event" from or to!
In order to change this, you need to make sure that by the end of Page_Load, all of the controls you want to fire events have been created. So you must recreate btnAwesome and add it to the panel before returning from Page_Load if you want it to fire the click event.

Categories

Resources