Timlankey
Timlankey

Reputation: 1

How to call a textbox dynamically from a string C# WPF?

So I have 70 "nodes" which are all textboxes in WPF and I'm trying to change the value in the textbox from a function call.

I have a function called:

private void changeNode(int row, int column, int cost)  
{    
       int nodeNumber= row * 10 + column;     
       call node"nodeNumber".Text = Convert.String(cost); 
       //example node0.Text = Convert.String(cost); 
}

I determine what node I want to change then call nodeX.Text to change it however I want X to be a variable that I can rather than having to create 70 cases where I call the appropriate textbox.

I saw a couple of ways of doing this with reflection however it seemed to only work if the function had no parameters and also was within the function not a textbox in XAML.

Let me know if there is a simple way to convert say a string "node37" to call node37.Text = cost or something like that.

Upvotes: 0

Views: 1408

Answers (4)

abhishek
abhishek

Reputation: 2992

It is always better to use List when you are dealing with Data. Create an ObservableCollection with the DataObjects which you want to load, and now deal with the Data object rather than actual Controls.

In WPF, if you follow the rules, you should not point to the actual object. Check the sample application here : http://www.abhisheksur.com/2010/08/woring-with-icollectionviewsource-in.html

I think you will get the approach.

Upvotes: 0

dwidel
dwidel

Reputation: 1294

Are all your textboxes children of the same canvas or other control? Loop through the children and add the controls to a dictionary. Parse the name to get the number and use that as the key.

Upvotes: 0

OJ.
OJ.

Reputation: 29399

Sounds like your approach is wrong. Why do you have a set of strings which represent the names of the textboxes? You should instead have in-memory references to TextBox objects. If you have more than one, and you don't know how many there will be, then use an array of TextBox objects instead. You can index into the array with the number that represents the textbox you're looking to interact with.

Avoid the use of reflection, it is completely unnecessary here.

Upvotes: 1

Ceco
Ceco

Reputation: 1634

I assume you have put names for all your textboxes (you can do this dynamically if you haven't). Then you can use the answers for this question to find the appropriate control by name.

Upvotes: 0

Related Questions