2011-12-20 2 views
1

私はWindowsフォームプロジェクトで作業しています。私のフォームでは、すべての行に記入する必要がある列を持つDataGridがあります。WinForms DataGridView、必須の列を設定する

MS Mangement Studioと似たようなものを入手したいと思います。現在の行の必須セルが満たされていない場合、別の行を追加できませんでした。

どうすればいいですか?

答えて

3

CellValidiatingイベントを使用して列の値を確認します。

このような何か:

const int MandatoryColumnIndex = 1; 
    public Form1() 
    { 
     InitializeComponent(); 
     dataGridView1.CellValidating += new DataGridViewCellValidatingEventHandler(dataGridView1_CellValidating); 
     dataGridView1.RowValidating += new DataGridViewCellCancelEventHandler(dataGridView1_RowValidating); 

    } 

    private void dataGridView1_RowValidating(object sender, DataGridViewCellCancelEventArgs e) 
    { 

     if (dataGridView1.Rows[e.RowIndex].Cells[MandatoryColumnIndex].FormattedValue.ToString() == string.Empty) 
     { 
      e.Cancel = true; 
      dataGridView1.Rows[e.RowIndex].Cells[MandatoryColumnIndex].ErrorText = "Mandatory"; 
     } 
     else 
     { 
      dataGridView1.Rows[e.RowIndex].Cells[MandatoryColumnIndex].ErrorText = string.Empty; 
     } 
    } 

    private void dataGridView1_CellValidating(object sender, DataGridViewCellValidatingEventArgs e) 
    { 
     if (e.ColumnIndex == MandatoryColumnIndex) 
     { 
      if (e.FormattedValue.ToString() == string.Empty) 
      { 
       dataGridView1[e.ColumnIndex, e.RowIndex].ErrorText = "Mandatory"; 
       e.Cancel = true; 
      } 
      else 
      { 
       dataGridView1[e.ColumnIndex, e.RowIndex].ErrorText = string.Empty; 
      }   
     } 
    } 
+0

私は、コードのあなたの部分をしようとしていますが、何か問題があります:私はそれが動作必須のセルを編集した場合、私は唯一の他のセルを埋める場合は、必須の空を残します、私はすべての行を追加することができます。それは良くありません – davioooh

+0

'RowValidating'イベントも使用できます。私は例を示すためにコードを修正しました。 – Dave

+0

素晴らしい!できます!ありがとうございました! (私は 'RowValidating'イベントだけを使って解決しました) – davioooh

関連する問題