I know how to create a dynamic control in c#:
TextBlock tb = new TextBlock();
tb.Text = "This is a new textblock";
But how would I reference this newly created control through code?
I browsed the net for a solution, and came across this code:
TextBlock tb = (TextBlock)this.FindName("TB");
tb.Text = "Text property changed";
Every time I create a new control with a name I get an exception:
TextBlock tb = new TextBlock();
tb.Text = "This is a new textblock";
tb.Name = "TB";
"The parameter is incorrect."
What am I doing wrong? Any help would be greatly appreciated.
Thanks in advance.
The Exception "The parameter is incorrect." may be occurring because of the duplicate names of the controls created.
For the dynamic control part : you must be adding that control to some Grid or Stackpanel or something. you can reference that dynamic control by getting the content or children of the parent control.
Like :
TextBlock Tb= new TextBlock();
tb.Text = "Hello";
ContentPanel.Children.Add(Tb);
//to reference :
var content = ContentPanel.Children;
foreach(UIElement uiElem in content)
{
if(uiElem.GetType() == typeof(TextBlock))
{
TextBlock tb = uiElem as TextBlock;
tb.Text = "Hyee";
}
}
Hope, it might help.
(Note: I have written this code directly here and not copied from VS, so please check syntax and spellings.)
Yes you can use reference dynamic controls this way.
But another way is that you can also keep a list of the references when you create the controls.
Related
I am trying to create a large number of checkboxes and felt it would not be efficient if I created them in the xaml.
Is it possible to dynamically create checkboxes and specify the group box/grid and its location in C# only? I know we can dynamically create the check boxes but I am not too sure how to manage its location via c#.
I am relatively new to WPF, thanks!
#user2584960 "Once I created them, how can I reference them? I am stuck... I gave the checkbox a name before adding to children but cannot reference them... "
I can only imaging you're trying to do:
Checkbox c = panel.Children.Add(new Checkbox());
You're not returning anything when you add to the panel, so you cant "Reference" a checkbox class.
As #Alex G was saying, his answer is showing how you add to the content window if you need to set a refrence just create a new class then add it to the window:
StackPanel panel = new StackPanel();
this.Content = panel;
CheckBox c = new CheckBox();
c.IsChecked = true;
//you Could create a loop to loop all of the list checkboxes to add them.
panel.Children.Add(c);
most likely you have a Page that has Content property
you should be able to do following
StackPanel panel = new StackPanel();
this.Content = panel;
panel.Children.Add(new CheckBox());
panel.Children.Add(new CheckBox());
panel.Children.Add(new CheckBox());
I guess you can reference them as following
CheckBox cb = new CheckBox();
panel.Children.Add(cb);
i have created a usercontrol, then i have a tabcontrol where in there is a tabpage that contains a 2 buttons, when button1 is clicked, it creates a new tabpage and the user control is added to its controls through
tab = new TabPage();
UserControl1 uc = new UserControl1();
tab.Controls.Add(uc);
tab.Name = "0";
tab.Text = tab.Name;
tabControl1.TabPages.Add(tab);
now when i click the button2, it should put text in the textbox inside the usercontrol-tabpage that was just created, i implemented it with this code,
TextBox sel = (TextBox)tabControl1.TabPages["0"].Controls["textBox1"];
sel.Text = "ssss";
but it returns a runtime error, saying that it cannot find the said control, so i tried
TextBox sel = (TextBox)tabControl1.TabPages["0"].Controls[0];
sel.Text = "ssss";
but it still returns a runtime error, saying that the cast usercontrol cannot be applied to textbox. i dont know what that means.. pls help me in this.. i also tried putting in Controls[1] but it returned a runtime error, of which is a OutofBounds exception. i dont know what to do, or how to find the control inside the usercontrol in the tabpage... pls hellp
It's a little bit unclear if the TextBox already exists in the UserControl, so I will assume it does. In that case, you have to reference the UserControl first:
UserControl1 uc1 = tabControl1.TabPages["0"].Controls[0] as UserControl1;
if (uc1 != null) {
TextBox sel = uc1.Controls["textBox1"] as TextBox;
if (sel != null) {
sel.Text = "ssss";
}
}
UserControl uc = NameTabPages.Controls[0] as UserControl; // it's work
I am new at C# & XAML development. I created a metro app with several textboxes. These textboxes are loaded in XAML data through a StackPanel in C# code, it has to be hardcoded. The problem is, I have no clue how I can add some empty spaces between every single textbox. Has anyone an idea?
The Code :
private void AddLastestCreatedField()
{
// Load the last created Field From DB
DBFunction.FieldTypes latestField;
DBFunction.Class1 myDBClass = new DBFunction.Class1();
latestField = myDBClass.GetLastestField();
// add new textbox and put it on the screen
var dragTranslation = new TranslateTransform();
//Generate the TextBox
TextBox fieldTextBox = new TextBox();
fieldTextBox.Name = "fieldTextBox_" + latestField.ID.ToString();
fieldTextBox.FontSize = 15;
fieldTextBox.Background.Opacity = 0.8;
ToolTip toolTip = new ToolTip();
toolTip.Content = latestField.Description;
ToolTipService.SetToolTip(fieldTextBox, toolTip);
fieldTextBox.IsReadOnly = true;
// Add Drag and Drop Handler for TextBox
fieldTextBox.ManipulationMode = ManipulationModes.All;
fieldTextBox.ManipulationDelta += fieldTextBox_ManipulationDelta;
fieldTextBox.ManipulationCompleted += fieldTextBox_ManipulationCompleted;
fieldTextBox.RenderTransform = dragTranslation;
dragTranslationDict.Add(fieldTextBox.Name, dragTranslation);
fieldTextBox.RenderTransform = dragTranslation;
// Add TextBox to a List to control later
TxtBoxList.Add(fieldTextBox);
// Generate TextBlock for each TextBlock
TextBlock fieldTextBlock = new TextBlock();
// fieldTextBlock.Name = "fieldTextBlock_" + cnt.ToString();
fieldTextBlock.TextAlignment = TextAlignment.Right;
fieldTextBlock.HorizontalAlignment = Windows.UI.Xaml.HorizontalAlignment.Right;
fieldTextBlock.Name = "fieldTextBlock_" + latestField.ID.ToString();
fieldTextBlock.Text = latestField.Name;
fieldTextBlock.FontSize = 15;
fieldTextBlock.Height = 33;
// Add Drag and Drop Handler for TextBlock
var dragTranslation2 = new TranslateTransform();
fieldTextBlock.RenderTransform = dragTranslation2;
dragTranslationDict2.Add(fieldTextBlock.Name, dragTranslation2);
// Add TextBlock to a list to control later
TxtBlockList.Add(fieldTextBlock);
TextBoxStack.Children.Add(fieldTextBox);
TextBlockStack.Children.Add(fieldTextBlock);
}
I'll skip the usual "What have you tried?" question and say you probably can get what you need by setting the Margin property on the TextBox - the Margin property will add "space" around the control size as a sort of padding (not to be confused with the Padding property, which will add space inside the control extents)
I don't know what you are really up to, but either use the Margin-property of the textbox. It defines, how much space there will be around the control,
See MSDN for more information.
I have created a textBox control on run-time for my winform application. The control appears just find once the form loads up, and works great too. However, I have just run into a problem as I realize I do not know how to write the code to write to a dynamically created control.
Let's assume I have created a button (named "Button1") on design time. In Button1's click event, (Button1_Click), I would like to write the word "Hello" to a textBox control that won't be created until the application is executed. Some code below:
C# Code:
// Create the textBox control
TextBox new_textBox = null;
int x = 10;
int y = 10;
int xWidth = 300;
int yHeight = 200;
new_textBox = new TextBox();
new_textBox.Text = controlText;
new_textBox.Name = "textBox" + controlName;
new_textBox.Size = new System.Drawing.Size(xWidth - 10, yHeight - 10);
new_textBox.Location = new Point(x, y);
new_textBox.BringToFront();
new_textBox.Multiline = true;
new_textBox.BorderStyle = BorderStyle.None;
// Add the textBox control to the form
this.Controls.Add(new_textBox);
The Problem:
From Button1_Click event, I cannot get in contact with a control that has not even been created yet. Thus, Visual Studio will throw an obvious error that the control does not exist (because it doesn't).
So, is there some way to dynamically call a control, and more
specifically, a textBox control?
Thank you for any help on the matter,
Evan
Declare the new_textBox at class scope. Then the compiler can access it. For example:
class MyForm
{
TextBox new_textBox;
void InitializeTextBox()
{
new_textBox = new TextBox();
// initialization code here
// Add it to the form
this.Controls.Add(new_textBox);
}
void Button1_Click(...)
{
new_textBox.Text = "clicked";
}
You can make the new_textBox a class member (member of the form). You can again assign it a value and add to the forms controls later dynamically.
It would be a good practice to check if is null in the buttonClick event, though.
What I want to do is to create something like that hotmail/facebook-style list of selected contacts.. with 1 little block and a "X" for removing each item.
How could I achieve that in .NET?
I thought of creating new labels "on the fly" and use .NET's Ajax UpdatePanel..
But, can I do it? if yes, how can i create a label on the fly, and put it just where I want?
I want the items to be created in a list. (<ul>)
Assuming you have a Panel somewhere on your site:
Label myLabel = new Label();
myLabel.Text = "My Name";
myLabel.CssClass = "labelClass";
pnlItems.Controls.Add(myLabel);
To have ul / li items (or something completely customisable):
HtmlGenericControl ulControl = new HtmlGenericControl("ul");
pnlItems.Controls.Add(ulControl);
foreach (object myThing in myItems)
{
HtmlGenericControl itemControl = new HtmlGenericControl("li");
itemControl.InnerHtml = myThing.GetMarkup();
ulControl.Controls.Add(itemControl);
}
Note this is untested - I'm fairly sure you can add controls to an Html Generic Control.