0
我有一個非常簡單的表,其中包含兩個標記爲唯一的字符串列。任何人都可以告訴我如何連接datagridview允許最基本的crud操作。我打算只使用網格而不使用其他控件。這意味着有一個刪除操作的鏈接列。Winforms DataGridView SQL小型CRUD示例
我已經嘗試了百萬次迭代有數據表,綁定源,數據適配器,命令建設者..
非常感謝。
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);
}
}
}
這已經讓我感動轉發沒有結束,謝謝大家。我仍然有刪除記錄的問題。 – Neil 2012-04-24 13:23:56
你的表必須有一個主鍵 - 是嗎? – ErikEJ 2012-04-25 08:42:06
是的,我有一個主鍵,最後我只使用了導航控件,它有一個刪除按鈕。 – Neil 2012-05-04 13:53:33