/// <summary> /// Here we pass in a strong typed class which represents the current row in the master /// DataGridView and also a list of valid contact titles. /// </summary> /// <param name="pCustomerRow"></param> /// <param name="pTitles"></param> public CustomerEditForm(NorthWindDataSet.CustomersRow pCustomerRow, List <string> pTitles) { InitializeComponent(); customerRow = pCustomerRow; companyNameTextBox.Text = customerRow.CompanyName; contactNameTextBox.Text = customerRow.ContactName; titleComboBox.DataSource = pTitles; titleComboBox.SelectedIndex = titleComboBox.FindString(customerRow.ContactTitle); }
/// <summary> /// Here when the user presses ENTER we display a modal form with /// the current row data. /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void CustomersDataGridView_KeyDown(object sender, KeyEventArgs e) { /* * We are on a new row, nothing to edit. * If you wanted this could be a starting point to add a new row * yet there are better ways, for starters using the add button in * the BindingNavigator. */ if (customersDataGridView.CurrentRow.IsNewRow) { return; } if (e.KeyData == Keys.Enter) { e.Handled = true; var id = ((DataRowView)customersBindingSource.Current).Row.Field <int>("CustomerIdentifier"); NorthWindDataSet.CustomersRow cust = northWindDataSet.Customers.FirstOrDefault(c => c.CustomerIdentifier == id); var f = new CustomerEditForm(cust, contactTitles); try { if (f.ShowDialog() != DialogResult.OK) { northWindDataSet.Customers.FirstOrDefault(c => c.CustomerIdentifier == id).RejectChanges(); } else { // nothing required here. If you were thinking validation should be done here, nope // validation should be in the edit form, see my comments in the save button for the // edit form. } } finally { f.Dispose(); } } }