On a tab page, there are 33 textboxes and I'm trying to get the values of textboxes with tabindex 13 through 33. I've set all the tab indexes to these numbers but cannot get it to work for some reason.
The code I currently have:
int startTabIndex = 13; int endTabIndex = 33; foreach (Control ctrl in Controls) { if (ctrl is TextBox) { if (ctrl.TabIndex == startTabIndex || ctrl.TabIndex <= endTabIndex) { MessageBox.Show(ctrl.Text); } } }
The MessageBox.Show(ctrl.Text)
is just a test to see if it is working.
Also, can this be accomplished by using LINQ, and how?
I changed my code to use LINQ to grab values of textboxes (the name and the text) per the answer provided by Steve. How exactly would I go about checking if the values were passed (like showing the text in a message box or something)?
int startTabIndex = 13; int endTabIndex = 33; System.Collections.Generic.Dictionary<string, string> dictionary = Controls.OfType<TextBox>() .Where(t => t.TabIndex >= startTabIndex && t.TabIndex <= endTabIndex) .Select(x => new System.Collections.Generic.KeyValuePair<string, string>(x.Name, x.Text)) .ToDictionary(z => z.Key, z => z.Value); foreach (var d in dictionary) { MessageBox.Show(d.Value); }
When I click on the insert button, nothing happens. Is there something I am missing?
Steve gave me an excellent example and it works but it starts at the end of the textboxes (tabindex 33) and proceeds all the way backwards to the beginning (tabindex 13). How to reverse this?
1 Answers
Answers 1
You can do that in one line with OfType (to get only textboxes) a Where (to select just the textboxes inside the tabindex range) and finally a Select to extract the strings from the Text property of the TextBoxes
int startTabIndex = 13; int endTabIndex = 33; List<string> texts = Controls.OfType<TextBox>() .Where(t => t.TabIndex >= startTabIndex && t.TabIndex <= endTabIndex) .OrderBy(b => b.TabIndex) .Select(x => x.Text).ToList();
To get a Dictionary<string,string>
the code could be changed to
Dictionary<string, string> dic = Controls.OfType<TextBox>() .Where(t => t.TabIndex >= startTabIndex && t.TabIndex <= endTabIndex) .OrderBy(b => b.TabIndex) .Select(x => new KeyValuePair<string,string>(x.Name, x.Text) .ToDictionary(z => z.Key, z => z.Value); foreach(KeyValuePair<string,string>kvp in dic) MessageBox.Show($"Key={kvp.Key} = {kvp.Value}");
UPDATE
Added also the OrderBy to ensure an enumeration according to the TabIndex to answer the last request of the OP (thanks to CodingYoshi).
0 comments:
Post a Comment