2015-10-13 68 views
0

的BindingSource聯編輯我有dataGridView1具有被定義爲數據源的BindingSource:的DataGridView與存儲過程

BindingSource bs = new BindingSource(); 
    bs.DataSource = dsGrid.Tables[0]; 
    dataGridView1.DataSource = bs; 

其中dsGrid是數據集從MSSQL DB與存儲的過程讀出。 當我設置dataGridView1.ReadOnly = false時,用戶可以內聯編輯數據。

我想在用戶完成編輯後將整個編輯的行發送到存儲過程,其中參數將被編輯爲數據。我該怎麼做?

我有類,它在實際的SqlConnection上運行此過程。所以我的目標是勾住發佈數據的時刻,並從網格中讀取編輯過的數據。比我可以將它們發送給DB。

+0

我不熟悉將DataGrid設置爲ReadOnly = false的行爲,但是您可以在這裏使用IValueConverter嗎? –

回答

1

我沒有找到簡單直接的解決方案。所以我添加了名爲Action的DataGridViewButtonColumn類的編輯列,其中帶有文本Edit的按鈕。

int _rowIndex = -1; 
bool _edited = false; 
. 
. 
. 
private void dataGridView1_CellClick(object sender, DataGridViewCellEventArgs e) 
{ 
    if (e.ColumnIndex == 0) // it is button - column Action 
    { 
     if (_rowIndex >= 0) // not first editing 
     { 
      if (_rowIndex != e.RowIndex) // row change - cancel and begin elsewhere 
      { 
       // TODO: ask for save edited values 
       endInlineEdit(_rowIndex); 
       beginInlineEdit(e.RowIndex); 
      } 
      else // the same row 
      { 
       if (_edited) // is edited, so save 
       { 
        saveToDB(e.RowIndex); 
       } 
       else // repeating same row editation 
       { 
        beginInlineEdit(e.RowIndex); 
       } 
      } 
     } 
     else // editing first time 
     { 
      beginInlineEdit(e.RowIndex); 
     } 
    } 
} 

private void saveToDB(int rowIndex) 
{  
    save to DB 
    ... 
    endInlineEdit(rowIndex); 
} 

private void beginInlineEdit(int rowIndex) 
{ 
    dataGridView1.Rows[rowIndex].Cells[0].Value = "Save"; 
    dataGridView1.CurrentCell = dataGridView1.Rows[rowIndex].Cells["FirstEditedColumn"]; 
    dataGridView1.EditMode = DataGridViewEditMode.EditOnEnter; 
    dataGridView1.BeginEdit(true); 
    _rowIndex = rowIndex; 
    _edited = true; 
} 

private void endInlineEdit(int rowIndex) 
{ 
    dataGridView1.Rows[rowIndex].Cells[0].Value = "Edit"; 
    dataGridView1.EditMode = DataGridViewEditMode.EditProgrammatically; 
    dataGridView1.EndEdit(); 
    _edited = false; 
} 

private void dataGridView1_RowLeave(object sender, DataGridViewCellEventArgs e) 
{ 
    if (_edited) 
    { 
     endInlineEdit(_rowIndex); 
    } 
} 

所以我做了手動。不好,但功能上。