C# Windows Forms应用中基于ComboBox选中项字符规则加载对应年龄组患者数据到TextBox的实现方案
Solution for Conditional Logic in ComboBox Selected Index Changed Event
Hey there! Let's work through this problem step by step. First, we'll fix a critical security issue in your existing code, then build the conditional logic you need to populate TextBoxes based on the patient's name.
Step 1: Fix SQL Injection Risk & Resource Management
Your current code uses direct string concatenation for the SQL query, which leaves you open to SQL injection attacks. We'll switch to parameterized queries, and use using statements to ensure database resources are properly cleaned up even if an error occurs.
Step 2: Add Conditional Logic Based on Patient Name
We'll check if the selected patient's name contains any letters from "ABC" or "DEF" (case-insensitively), then execute the corresponding logic to populate your TextBoxes.
Full Refactored Code
private void comboBox1_SelectedIndexChanged(object sender, EventArgs e) { // Clear other ComboBoxes and TextBoxes if selected text is empty if (string.IsNullOrWhiteSpace(comboBox1.Text)) { foreach (Control item in Controls) { if (item is ComboBox comboBox) { comboBox.Text = string.Empty; } } // Reset all TextBoxes to clean state textBox1.Clear(); textBox2.Clear(); textBox3.Clear(); textBox4.Clear(); textBox5.Clear(); return; } // Use using statements to auto-dispose database resources using (OleDbConnection connection = new OleDbConnection("Your_Connection_String_Here")) { try { connection.Open(); // Parameterized query to avoid SQL injection string query = "SELECT * FROM patient WHERE patient_name LIKE @PatientName"; using (OleDbCommand command = new OleDbCommand(query, connection)) { // Add wildcard for partial matches (adjust if you need exact matches) command.Parameters.AddWithValue("@PatientName", $"%{comboBox1.Text}%"); using (OleDbDataReader dataReader = command.ExecuteReader()) { if (dataReader.Read()) { string patientName = dataReader["patient_name"].ToString(); // Check if name contains any of A/B/C (case-insensitive) bool hasABC = patientName.IndexOfAny(new char[] { 'A', 'B', 'C' }, StringComparison.OrdinalIgnoreCase) >= 0; // Check if name contains any of D/E/F (case-insensitive) bool hasDEF = patientName.IndexOfAny(new char[] { 'D', 'E', 'F' }, StringComparison.OrdinalIgnoreCase) >= 0; if (hasABC) { // Populate 45-year-old group data to textBox1 and textBox2 // Replace placeholders with your actual column names/indices textBox1.Text = dataReader["Your_45Age_Data_Column1"].ToString(); textBox2.Text = dataReader["Your_45Age_Data_Column2"].ToString(); // Clear unused TextBoxes textBox3.Clear(); textBox4.Clear(); textBox5.Clear(); } else if (hasDEF) { // Populate 75-year-old group data to textBox1, textBox2, textBox3 textBox1.Text = dataReader["Your_75Age_Data_Column1"].ToString(); textBox2.Text = dataReader["Your_75Age_Data_Column2"].ToString(); textBox3.Text = dataReader["Your_75Age_Data_Column3"].ToString(); // Clear unused TextBoxes textBox4.Clear(); textBox5.Clear(); } else { // Default behavior: use your original TextBox population logic textBox2.Text = dataReader[1].ToString(); textBox3.Text = dataReader[21].ToString(); textBox4.Text = dataReader[19].ToString(); textBox5.Text = dataReader[15].ToString(); textBox1.Clear(); // Or set a default value if needed } } else { // No matching patient found, reset all TextBoxes textBox1.Clear(); textBox2.Clear(); textBox3.Clear(); textBox4.Clear(); textBox5.Clear(); } } } } catch (Exception ex) { // Handle errors gracefully for users MessageBox.Show($"Oops, something went wrong: {ex.Message}", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error); } } }
Key Details to Note:
- SQL Injection Protection: Parameterized queries ensure user input can't be interpreted as malicious SQL code.
- Case Insensitivity: Using
StringComparison.OrdinalIgnoreCasemakes the letter check work for both uppercase and lowercase names. - Resource Safety:
usingstatements automatically close connections and dispose objects, preventing resource leaks. - Clean State Handling: We added logic to reset all inputs when no patient is found or the ComboBox is empty, which makes the app feel more polished.
- Readability: Replace placeholder column names like
Your_45Age_Data_Column1with your actual database column names (using names instead of indices makes code easier to maintain).
内容的提问来源于stack exchange,提问作者proje hesabı
相关产品推荐
相关产品推荐

