2013-01-05 14 views
5

Mam aplikację formularza systemu Windows, która zawiera dane datgridview. Muszę wymusić sprawdzanie poprawności komórek w komórkach datagridview, aby nie akceptował wartości ujemnych. Znalazłem odpowiedni kod dla niego z biblioteki msdn.Sprawdzania poprawności wartości komórek Datagridview w języku C#

private void dataGridView1_CellValidating(object sender, 
DataGridViewCellValidatingEventArgs e) 
{ 
dataGridView1.Rows[e.RowIndex].ErrorText = ""; 
int newInteger; 

// Don't try to validate the 'new row' until finished 
// editing since there 
// is not any point in validating its initial value. 
if (dataGridView1.Rows[e.RowIndex].IsNewRow) { return; } 
if (!int.TryParse(e.FormattedValue.ToString(), 
    out newInteger) || newInteger < 0) 
{ 
    e.Cancel = true; 
    dataGridView1.Rows[e.RowIndex].ErrorText = "the value must be a Positive integer"; 
} 
} 

Niestety kod pozwala tylko na wpisanie liczb całkowitych do datagridview. Ponieważ mam nazwę kolumny jako "Nazwa elementu", która ma być wprowadzona jako tekst, problem występuje w kodzie. Generuje komunikat o błędzie, gdy wpisuję nazwę elementu. Reszta sprawdzania poprawności działania działa doskonale! Jak mam edytować kod, aby nie generował tego błędu?

góry dzięki

Mirfath

Odpowiedz

4

DataGridViewCellValidatingEventArgse ma właściwość .ColIndex której można sprawdzić, aby upewnić się walidacja odbywa się tylko na kolumnę, którą chcesz.

private void dataGridView1_CellValidating(object sender, 
DataGridViewCellValidatingEventArgs e) { 
    if (e.ColIndex == dataGridView1.Columns["MyNumericColumnName"].Index) { 
     dataGridView1.Rows[e.RowIndex].ErrorText = ""; 
     int newInteger; 

     // Don't try to validate the 'new row' until finished 
     // editing since there 
     // is not any point in validating its initial value. 
     if (dataGridView1.Rows[e.RowIndex].IsNewRow) { return; } 
     if (!int.TryParse(e.FormattedValue.ToString(), 
      out newInteger) || newInteger < 0) 
     { 
      e.Cancel = true; 
      dataGridView1.Rows[e.RowIndex].ErrorText = "the value must be a Positive integer"; 
     } 
    } 
} 
0

Wypróbuj ten i wymyśl go.

private void dataGridView1_CellValidating(object sender, DataGridViewCellValidatingEventArgs e) 
    { 
     if (dataGridView1.IsCurrentCellDirty) 
     { 
      if (e.ColumnIndex == 0) //<-Column for String 
      { 
       Console.WriteLine(dataGridView1[e.ColumnIndex, e.RowIndex].EditedFormattedValue.ToString()); 
       //Your Logic here 
      } 
      if (e.ColumnIndex == 1) //<-Column for Integer 
      { 
       Console.WriteLine(dataGridView1[e.ColumnIndex, e.RowIndex].EditedFormattedValue.ToString()); 
       //Your Logic here 
      } 
     } 
    } 
Powiązane problemy