c#, wpf, Dynamically naming controls - c#

How do i create a new Button/Canvas with a dynamic name?
Button {buttonname read from text file} = new Button;
I have googled this for a while now but i can't find the solution.
Thank you!

I'm not sure if I understood correctly, but that name in your example is not the button name, it's just the reference name used in code to access the button. The button name would be set like this:
buttonRefName.Name = "ButtonName1";
So you can set the name to whatever you want: dynamically generated names inside a loop, names read from a file, etc...
You can use the same reference name for multiple buttons, just be sure to add it to List or to WPF Window, Panel, etc... before creating the new one:
var buttonList = new List<Button>();
var buttonRef = new Button { Name = "YourButtonName" };
buttonList.Add(buttonRef);
buttonRef = new Button { Name = "YourButtonName2" };
buttonList.Add(buttonRef);

It not possible the way you want to do it. If you are reading from a text file better use a List or better a Dictionary... an example use is as follows:
var buttons = new Dictionary<string, Button>();
buttons["yourName"] = new Button();
// logic goes here

Related

generate button for each list

I have a series of lists in a static class (used as a global class)
public static class globalClass
{
public static List<classA> aList = new List<classA>();
public static List<classB> bList = new List<classB>();
public static List<classC> cList = new List<classC>();
}
I want to generate a xaml button for each list, and was told reflection was a bad idea. This is how I handled it using reflection.
//get FieldInfo for globalClass
TypeInfo typeInfo = IntrospectionExtensions.GetTypeInfo(typeof(globalClass));
IEnumerable<FieldInfo> FieldInfoList = typeInfo.DeclaredFields;
foreach (FieldInfo f in FieldInfoList)
{
//Only look at lists
if(f.FieldType.ToString().StartsWith("System.Collections.Generic.List`1")){
StackPanel s = new StackPanel();
s.Orientation = Orientation.Horizontal;
TextBlock textBlock = new TextBlock();
textBlock.FontSize = 45;
textBlock.Text = f.Name.ToString();
Button addButton = new Button();
addButton.Click += delegate(object sender, RoutedEventArgs e)
{
Frame.Navigate(typeof(addObjectToLibraryPage), f);
};
addButton.Margin = new Thickness(10);
addButton.Name = "addButton";
addButton.Content = "add";
Button deleteButton = new Button();
deleteButton.Click += delegate(object sender, RoutedEventArgs e)
{
Frame.Navigate(typeof(deleteObjectFromLibraryPage), f);
};
deleteButton.Margin = new Thickness(10);
deleteButton.Name = "deleteButton";
deleteButton.Content = "delete";
s.Children.Add(addButton);
s.Children.Add(deleteButton);
//add new textBlock and stackpanel to existing xaml
stackPanel.Items.Add(textBlock);
stackPanel.Items.Add(s);
}
}
Is there any cleaner way to do this? Hopefully I would like to be able to pass the actual list instead of a FieldInfo.
I don't want to have to handle each list individually because I may end up with 20+ lists and am using them all in a very similar way.
An example of what I am trying to do:
Suppose I have a grocery/nutrition App, and I want users to be able to record what they eat/need from the store. They can select from a list of Fruit, Vegetables, Meat, Dairy, Sweets, Canned Goods, Etc..
But, I want them to be able to (as an advanced option) be able to edit the list of possible fruits, or any other food category. And I don't want to just have a list of "food" because meat will record things like minimum cooking temperature or something like that.
So, under advanced options, I would want two buttons for each category (add to fruit, delete from fruit). And theoretically add an Import/Export page so I can share my list of fruits with other people or something.
It doesn't seem like the answers pointing to using a superclass will work. See: C# polymorphism simple question
You can create a list to contain all the existing lists you have. You can then iterate over the list to create the buttons. If you wish to maintain a label for each list you could use a dictionary with the key as the label text and list as the value.
The proposed solution aside, do take into account the comments given from Sayse.

How to retrieve text from a TextBox that was created programatically

Alright, so I have a form set up that contains a label and a button. When the button is pressed it creates several labels and and two textfields in a specific area.
I cannot for the life of me, figure out how to retrieve the text from those textfields and store it in a public string.
Any help would be wonderful and greatly appreciated.
Edit: As per request.
TextBox playertextbox = new TextBox();
playertextbox.Location = new Point(460, 200);
this.Controls.Add(playertextbox);
You can assign a name to the textbox and later use ControlCollection.Find to retrieve it
Try this
TextBox playertextbox = new TextBox();
playertextbox.Location = new Point(460, 200);
playertextbox.Name = "playertxtBox"; // Add some name
this.Controls.Add(playertextbox);
Then use the name in the button click handler or similar :
//Use that name to search here
TextBox playertextbox = ((TextBox) this.Controls.Find("playertxtBox",true)[0]);
string text = playertextbox.Text;

Open form with Form Name in winform appliaction

I want to ask what should i do to open form with the help or class name in winform c#?
I have three different forms
UserManagement
GroupsManagement
LocationManagement
I get permission from database for these three forms
in menu click i fill tag Property with the name of form like this
tsmMain.Tag = item.PermissionName
tsmMain.Click += new EventHandler(tsmMain_Click);
what i want to do is to open form dynamically in button click and to remove these if condition?
Can i do this with reflection or else??
ToolStripMenuItem aa = sender as ToolStripMenuItem;
var tag = aa.Tag;
if (tag == "User Management")
{
UserManagement oUserForm = new UserManagement();
oUserForm.Show();
}
if (tag == "Groups Management")
{
GroupManagement oGroupForm = new GroupManagement();
oGroupForm.Show();
}
You may be able to do something like this, using the name of your form, as a string argument:
var form = (Form)Activator.CreateInstance(Type.GetType("YourNameSpace.UserManagement"));
form.Show();
One straightforward, but not necessarily very clean solution would be to store the forms right there in the Tag property of your menu items, rather than the strings.
Somewhere at the beginning of your application, you'd have to assign these instances:
myUserManagementItem.Tag = new UserManagement();
myGroupsManagementItem.Tag = new GroupManagement();
Then, in the click event, you could shorten your code to:
ToolStripMenuItem aa = sender as ToolStripMenuItem;
Form form = aa.Tag as Form;
form.Show();
Cleaner solutions would include the following:
Provide separate event handlers for different menu items.
Derive your own menu item types that store the form to show in a strongly-typed property.

How to create a textbox which has same attributes as another textbox?

I need to create and add some TextBoxes which has same attribute as some other TextBoxes.
Is there a way to copy the attributes to another ?
I'm looking for a one like solution. I know I can set variable one by one.
TextBox Old = new TextBox() {
Size = new System.Drawing.Size(25,25),
Location = new Point(a.row*25, a.col*25),
Multiline = true
};
TextBox New = new TextBox(); //which has same location,size as old one ?
EDIT The TextBox might be any other .NET controls !
You can use this Solution. You can write a extention and that get via Reflection all propertys
Please use the search function in future.
Create an initializer method:
private void InitializeTextBox(TextBox textBox)
{
textBox.Size = new System.Drawing.Size(25, 25);
textBox.Location = new Point(a.row * 25, a.col * 25);
textBox.Multiline = true;
}
And use like this:
TextBox t1 = new TextBox(), t2 = new TextBox();
InitializeTextBox(t1);
InitializeTextBox(t2);
Or a copier method:
private void CopyTextBoxProps(TextBox source, TextBox dest)
{
dest.Size = source.Size;
dest.Location = source.Location;
dest.Multiline = source.Multiline;
//...
}
and use it accordingly.
Probably the most straightforward way is this:
TextBox New = new TextBox {
Size = Old.Size,
Location = Old.Location,
Multiline = Old.Multiline
};
If this is something you need to do a lot, you could write an extension method that does the same thing:
public static class TextBoxExtensions {
public static TextBox Copy(this TextBox textBoxToCopy) {
var copiedTextBox = new TextBox {
copiedTextBox = textBoxToCopy.Size,
copiedTextBox = textBoxToCopy.Location,
copiedTextBox = textBoxToCopy.Multiline
};
}
}
Usage:
var copyOfOld = Old.Copy();
If you are going to add a lot more properties to copy, I'd think about using AutoMapper and defining a map between TextBox and TextBox. If you're interested in that path, let me know and I'll post a sample.
It would turn this into a one liner, but you'd need a dependency on AutoMapper, but it's available on NuGet: http://nuget.org/packages/AutoMapper/2.2.0
First, take a dependency on AutoMapper.
Define the mapping somewhere in your project:
Mapper.CreateMap<TextBox, TextBox>();
Usage:
var newTextBox = Mapper.Map<TextBox, TextBox>(Old);
or, if you already have an instance you want to stuff it into:
Mapper.Map(Old, newTextBox);
AFAIK, there is no built in, one line solution, so it's either the extension method, or take a dependency on AutoMapper. The extension method does not have to do it that way, you can use reflection or other choices there.
I use AutoMapper in just about all of my projects and it's invaluable.
You can define many mappings in your map definition, then all your copies become one liners. Well, besides the definition :)

How to Dynamically Create Tabs

This is in C#
I Need to basically make TabPages from a textbox.Text so for example:
textBox1.Text = "test";
TabPage textBox1.Text = new TabPage();
That is what i want to do.. i know that won't work directly, but that should give you the idea of how i want to create the tabPages.. then i want to be able to call them later on too so for example:
String browser = "browser 1";
(textBox1.Text as TabPage).Controls.Add(WebBrowser browser)
I need all the names to be dynamic because what this will be is a program that can run tests for customer accounts There would be a TabControl which has the "Account Number as the tabPage control name and then inside each of those tabPages would be another TabControl with a set up tabs with each invidivual test in it's own tab. So Tabs within Tabs basically.
Make it look similar to this:
var page = new TabPage(textBox1.Text);
var browser = new WebBrowser();
browser.Dock = DockStyle.Fill;
page.Controls.Add(browser);
tabControl1.TabPages.Add(page);
browser.Navigate("http://stackoverflow.com");
page.Select();
Actually one other thing i want to know, How can i call on this Tab # another time outside of this function?
This is basically what i turned out to look like.
String browserName = "Test Check";
var tabPageName = new TabPage(textBox1.Text);
var tabPageBrowser = new TabPage(browserName);
var tabPageTabControl = new TabControl();
var browser = new WebBrowser();
tabPageName.Controls.Add(tabPageTabControl);
tabPageTabControl.TabPages.Add(tabPageBrowser);
tabPageBrowser.Controls.Add(browser);
mainTabControl.TabPages.Add(tabPageName);
mainTabControl.SelectedTab = tabPageName;

Categories

Resources