如何在Patient Complaints窗体中将CheckBox选中值添加到DataGridView指定列?
Solution to Add Specific Column Values to DataGridView
Got it, here's how you can handle this scenario where you only populate specific columns based on checked CheckBoxes when the button is clicked:
Instead of passing all column values at once with Rows.Add(), you'll create a new row, set values only for the columns corresponding to checked CheckBoxes, then add that row to your DataGridView. Here's a step-by-step implementation:
Step 1: Handle the Button Click Event
Double-click your button to generate the click event handler, then add the following code inside it:
private void btnAddComplaints_Click(object sender, EventArgs e) { // Create a new row using the grid's template to match column structure DataGridViewRow newRow = new DataGridViewRow(); newRow.CreateCells(dgViewPComplaints); // Set values for each checked CheckBox's corresponding column if (chkSmoking.Checked) { // Replace "SmokingColumn" with your actual column name in DataGridView newRow.Cells["SmokingColumn"].Value = chkSmoking.Text; } if (chkChestPain.Checked) { newRow.Cells["ChestPainColumn"].Value = chkChestPain.Text; } if (chkFatigue.Checked) { newRow.Cells["FatigueColumn"].Value = chkFatigue.Text; } // Add more if blocks for your other CheckBoxes and their columns // Add the populated row to the DataGridView dgViewPComplaints.Rows.Add(newRow); }
Alternative Approach (Shorter Version)
You can also add the row first and then update its cells, which might feel more intuitive:
private void btnAddComplaints_Click(object sender, EventArgs e) { // Add a new empty row and get its index int newRowIndex = dgViewPComplaints.Rows.Add(); DataGridViewRow newRow = dgViewPComplaints.Rows[newRowIndex]; // Set values based on checked CheckBoxes if (chkSmoking.Checked) newRow.Cells["SmokingColumn"].Value = chkSmoking.Text; if (chkChestPain.Checked) newRow.Cells["ChestPainColumn"].Value = chkChestPain.Text; if (chkFatigue.Checked) newRow.Cells["FatigueColumn"].Value = chkFatigue.Text; // Repeat for other CheckBox-column pairs }
Key Tips for Robustness:
- Use Column Names: Referencing columns by their name (like
"SmokingColumn") is better than index numbers—if you reorder columns later, your code won't break. - Unchecked CheckBoxes: Columns for unchecked boxes will stay empty (or show their default value). If you want to explicitly set them to something like
""ornull, add anelseclause. - Reusable Code for Many CheckBoxes: If you have lots of CheckBoxes, avoid writing individual
ifblocks by using theTagproperty:- Set each CheckBox's
Tagproperty to match its corresponding DataGridView column name. - Use this loop to handle all CheckBoxes at once:
- Set each CheckBox's
foreach (Control ctrl in this.Controls) { if (ctrl is CheckBox chk && chk.Checked) { string columnName = chk.Tag.ToString(); newRow.Cells[columnName].Value = chk.Text; } }
内容的提问来源于stack exchange,提问作者Muhammad Noman
相关产品推荐
相关产品推荐

