C#:如何将数据源数据与表单输入数据添加至DataGridView同一行
Got it, let's break this down step by step—you're super close, the missing piece is properly binding your ComboBox to include both the employee name (for display) and employee ID (for hidden value access). Here's how to fix it:
1. Ensure Your ComboBox is Bound Correctly
First, when you load your employee data into the ComboBox, don't just set the DataSource—you need to specify two key properties to link the visible name to the underlying ID:
DisplayMember: The name of the field in your data source that holds the employee name (e.g.,"EmployeeName")ValueMember: The name of the field that holds the employee ID (e.g.,"EmployeeID")
Example initialization code (put this in your form's Load event):
// Assume you have a DataTable or List<Employee> named employeeData with EmployeeID and EmployeeName columns/properties comboEmployee.DisplayMember = "EmployeeName"; comboEmployee.ValueMember = "EmployeeID"; comboEmployee.DataSource = employeeData;
If you're using a custom Employee class instead of a DataTable, just make sure the property names match what you set for DisplayMember and ValueMember.
2. Add Row to DataGridView on Button Click
In your Add button's click event handler, you can now retrieve the selected employee ID using comboEmployee.SelectedValue. Then, construct a new row with all the required data and add it to your DataGridView.
Here's a complete example (assuming your DataGridView uses a DataTable as its data source—this is the most common approach):
private void btnAdd_Click(object sender, EventArgs e) { // First, validate inputs to avoid errors if (comboEmployee.SelectedItem == null) { MessageBox.Show("Please select an employee!"); return; } if (!int.TryParse(txtWeekNumber.Text, out int weekNumber)) { MessageBox.Show("Please enter a valid week number!"); return; } if (!decimal.TryParse(txtHours.Text, out decimal hoursWorked)) { MessageBox.Show("Please enter valid hours!"); return; } // Get the selected employee's ID and name int employeeId = (int)comboEmployee.SelectedValue; string employeeName = comboEmployee.Text; // Get or initialize the DataTable tied to your DataGridView DataTable dgvData = dgvEmployeeHours.DataSource as DataTable; if (dgvData == null) { // Create a new DataTable with required columns if it's the first addition dgvData = new DataTable(); dgvData.Columns.Add("EmployeeID", typeof(int)); dgvData.Columns.Add("EmployeeName", typeof(string)); dgvData.Columns.Add("WeekNumber", typeof(int)); dgvData.Columns.Add("HoursWorked", typeof(decimal)); dgvEmployeeHours.DataSource = dgvData; } // Add the new row to the DataTable (this auto-updates the DataGridView) DataRow newRow = dgvData.NewRow(); newRow["EmployeeID"] = employeeId; newRow["EmployeeName"] = employeeName; newRow["WeekNumber"] = weekNumber; newRow["HoursWorked"] = hoursWorked; dgvData.Rows.Add(newRow); }
3. Quick Tips
- If you're using a
BindingList<EmployeeHours>instead of a DataTable, just create a newEmployeeHoursobject (populated with ID, name, week, hours) and add it to the binding list—the DataGridView will update automatically. - Double-check the data type of your
SelectedValuecast (e.g., usestringif your employee IDs are alphanumeric instead ofint). - Keep input validation in place to prevent crashes from invalid user entries.
内容的提问来源于stack exchange,提问作者Shiela L

