pghtech
pghtech

Reputation: 3702

Group Textboxes to add them to a List from a Windows Form Application

I am working on a Windows Form Application and I want to allow the user to add groups of (2) data inputs - whether that is 2 textboxes or some other control. For each "set" they would be inputting text into each field. I would then iterate through each 'set' to a dictionary where one goes in as the key and the other the value. It will start with a default of 2 sets of inputs.

So my problem/question is:

1) Since I want to allow them to add a limit number of inputs (but unknown how many they will add), what would be the best control for doing this.

2) how do I group each 2 inputs together so I can add one field as the key and one as the value in a dictionary.

Any thoughts.

Upvotes: 0

Views: 1179

Answers (1)

AaronLS
AaronLS

Reputation: 38374

I would create a user control, put the two textboxes on it, with the designer names of KeyTextBox and ValueTextBox, then on the user control class, add two properties, one for the key and the other for the value.

Now let's say you have a "add text input Pair" button on your main form, and also an empty panel that will hold your list of buttons. In the code for that button you just new up an instance of your KeyValuePairTextBoxControl, then add it to the Panel's Controls collection.

Now whenever you want to create a dictionary based on these values you simply loop through the controls collection of that panel, and for each KeyValuePairTextBoxControl you can access it's key and value properties to place them in the dictionary.

You could also expose the text changed events of the textboxes through your user control and as you create each control you wire up some handler for these events so that you can refresh your dictionary each time.

You might be able to do this much cleaner with some data binding features, but generally that can get much more complicated depending on the details of what you want to do.

Upvotes: 2

Related Questions