I have a very simple table with two string columns marked unique. Can anyone tell me how to wire up the datagridview to allow the most basic crud operations. I intend to use only the grid and no additional controls. This means having a link column for the delete operation.
I have tried a million iterations of having data tables, binding sources, data adapters, command builders..
Many thanks.
void dataGridView1_DataError(object sender, DataGridViewDataErrorEventArgs e)
{
}
private void bindingSource_PositionChanged(object sender, EventArgs e)
{
// if the user moves to a new row, check if the
// last row was changed
BindingSource thisBindingSource =
(BindingSource)sender;
DataRow ThisDataRow =
((DataRowView)thisBindingSource.Current).Row;
if (ThisDataRow == _lastDataRow)
{
// we need to avoid to write a datarow to the
// database when it is still processed. Otherwise
// we get a problem with the event handling of
//the DataTable.
throw new InvalidOperationException("It seems the" +
" PositionChanged event was fired twice for" +
" the same row");
}
UpdateRowToDatabase();
// track the current row for next
// PositionChanged event
_lastDataRow = ThisDataRow;
}
private void UpdateRowToDatabase()
{
if (_lastDataRow != null)
{
if (_lastDataRow.RowState == DataRowState.Modified
|| _lastDataRow.RowState == DataRowState.Added
|| _lastDataRow.RowState == DataRowState.Deleted)
{
DataRow[] rows = new DataRow[1];
rows[0] = _lastDataRow;
_dataAdapter.Update(rows);
}
}
}
void dataGridView1_CellClick(object sender, DataGridViewCellEventArgs e)
{
Debug.WriteLine(string.Format("Click Col: {0} Row:{1}", e.ColumnIndex, e.RowIndex));
if (!_edit && e.ColumnIndex == 0)
{
if (e.RowIndex < _dataTable.Rows.Count)
{
DataRow[] rows = new DataRow[1];
rows[0] = _dataTable.Rows[e.RowIndex];
_bindingSource.RemoveCurrent();
_dataAdapter.Update(rows);
}
}
}
See the ResultSetGrid class in the CodePlex project here: http://sqlcetoolbox.codeplex.com/SourceControl/changeset/view/77500#1210725