C#中如何验证用户在10个文本框输入的字母数字值是否按升序排列
Let's walk through implementing this feature with your existing code. I'll cover collecting input, validating the order, and showing clear feedback to the user.
Step 1: Prepare a Collection of TextBoxes
First, make it easier to work with all 10 text boxes by storing them in a list. Add this to your form's class:
private List<TextBox> _inputTextBoxes; private void Form1_Load(object sender, EventArgs e) { // Replace with your actual text box names (textBox1 to textBox10) _inputTextBoxes = new List<TextBox> { textBox1, textBox2, textBox3, textBox4, textBox5, textBox6, textBox7, textBox8, textBox9, textBox10 }; }
Don't forget to hook up the Form1_Load event in your form's designer (or via code) so it runs when the form opens.
Step 2: Update Random List Generation (Optional but Useful)
To keep track of the exact strings the user needs to sort, store the shuffled list as a class-level variable. This lets us generate the correct sorted version later:
private List<string> _currentRandomList; private void button1_Click(object sender, EventArgs e) { listBox1.Items.Clear(); var originalList = new List<string> { "12fe", "46ge", "7uf", "15gs", "64ku", "42nt", "04bv", "07nh", "03lf", "86nj" }; var random = new Random(); // Create a shuffled copy of the original list _currentRandomList = originalList.OrderBy(x => random.Next()).ToList(); foreach (var item in _currentRandomList) { listBox1.Items.Add(item); } // Clear input boxes when generating a new list foreach (var textBox in _inputTextBoxes) { textBox.Clear(); } }
Step 3: Implement Validation Logic in button2_Click
This is where we check if the user's input is correctly sorted. I've included two validation options—pick whichever fits your needs:
- Check if input matches the sorted version of the random list (ensures users used exactly the provided strings in order)
- Check if input is itself in ascending order (allows any 10 alphanumeric values as long as they're sorted)
private void button2_Click(object sender, EventArgs e) { // Step 1: Collect user input and check for empty fields var userInput = new List<string>(); bool hasEmptyInput = false; foreach (var textBox in _inputTextBoxes) { string input = textBox.Text.Trim(); if (string.IsNullOrEmpty(input)) { hasEmptyInput = true; break; } userInput.Add(input); } if (hasEmptyInput) { MessageBox.Show("Please fill all 10 text boxes!", "Input Error", MessageBoxButtons.OK, MessageBoxIcon.Warning); return; } // Option 1: Validate input matches the sorted random list (exact values in order) var sortedCorrectList = _currentRandomList.OrderBy(x => x).ToList(); bool isExactMatch = userInput.SequenceEqual(sortedCorrectList); if (isExactMatch) { MessageBox.Show("Perfect! You entered the values in the correct ascending order.", "Success", MessageBoxButtons.OK, MessageBoxIcon.Information); return; } // Option 2: Validate if user's input is itself in ascending order (any valid alphanumeric values) bool isSortedAscending = true; for (int i = 0; i < userInput.Count - 1; i++) { // Use ordinal comparison for standard alphanumeric sorting if (string.Compare(userInput[i], userInput[i+1], StringComparison.Ordinal) > 0) { isSortedAscending = false; break; } } if (isSortedAscending) { MessageBox.Show("Your input is in ascending order, but doesn't match the expected values from the list.", "Partial Success", MessageBoxButtons.OK, MessageBoxIcon.Information); } else { MessageBox.Show("Oops! Your input is not in ascending order. Please try again.", "Validation Failed", MessageBoxButtons.OK, MessageBoxIcon.Error); } }
Step 4: Optional - Restrict Input to Valid Strings
To prevent users from entering values not in the random list, hook all 10 text boxes to this shared TextChanged event:
private void textBox_TextChanged(object sender, EventArgs e) { var textBox = sender as TextBox; if (textBox == null || _currentRandomList == null) return; string input = textBox.Text.Trim(); if (!string.IsNullOrEmpty(input) && !_currentRandomList.Contains(input)) { // Highlight invalid input textBox.BackColor = Color.LightPink; // Optional: Clear invalid input after a short delay // textBox.Text = ""; } else { textBox.BackColor = SystemColors.Window; } }
Key Notes:
- String Comparison:
StringComparison.Ordinalfollows standard Unicode order (digits before letters, uppercase before lowercase). UseStringComparison.OrdinalIgnoreCaseif you need case-insensitive sorting. - Empty Input Check: Always validate all fields are filled first to avoid errors during sorting checks.
内容的提问来源于stack exchange,提问作者sudesh

