다음을 통해 공유


방법: Windows Forms DataGrid 컨트롤을 사용하여 입력 유효성 검사

비고

ToolStrip 컨트롤은 ToolBar 컨트롤을 대체하고 여기에 다른 기능을 추가하여 새로 도입된 컨트롤이지만 이전 버전과의 호환성 및 이후 사용 가능성을 고려하여 ToolBar 컨트롤을 계속 유지하도록 선택할 수 있습니다. 자세한 내용은 Windows Forms DataGridView 컨트롤과 DataGrid 컨트롤의 차이점을 참조하세요.

Windows Forms DataGrid 컨트롤에 사용할 수 있는 입력 유효성 검사에는 두 가지 유형이 있습니다. 사용자가 셀에 사용할 수 없는 데이터 형식의 값(예: 정수에 문자열)을 입력하려고 하면 새로운 잘못된 값이 이전 값으로 바뀝니다. 이러한 종류의 입력 유효성 검사는 자동으로 수행되며 사용자 지정할 수 없습니다.

다른 유형의 입력 유효성 검사를 사용하여 허용할 수 없는 데이터(예: 1보다 크거나 같아야 하는 필드에서 0 값 또는 부적절한 문자열)를 거부할 수 있습니다. 이 작업은 데이터 세트에서 ColumnChanging 또는 RowChanging 이벤트에 대한 이벤트 처리기를 작성하여 수행됩니다. 아래 예제에서는 특히 “제품” 열에 대해 허용되지 않는 값이 거부되므로 ColumnChanging 이벤트를 사용합니다. RowChanging 이벤트를 사용하여 “종료 날짜” 열의 값이 같은 행의 “시작 날짜” 열보다 나중인지를 확인할 수 있습니다.

사용자 입력의 유효성을 검사하려면

  1. 적절한 테이블에 대한 ColumnChanging 이벤트를 처리하는 코드를 작성합니다. 부적절한 입력이 감지되면 SetColumnError 개체의 DataRow 메서드를 호출합니다.

    Private Sub Customers_ColumnChanging(ByVal sender As Object, _
    ByVal e As System.Data.DataColumnChangeEventArgs)
       ' Only check for errors in the Product column
       If (e.Column.ColumnName.Equals("Product")) Then
          ' Do not allow "Automobile" as a product.
          If CType(e.ProposedValue, String) = "Automobile" Then
             Dim badValue As Object = e.ProposedValue
             e.ProposedValue = "Bad Data"
             e.Row.RowError = "The Product column contains an error"
             e.Row.SetColumnError(e.Column, "Product cannot be " & _
             CType(badValue, String))
          End If
       End If
    End Sub
    
    //Handle column changing events on the Customers table
    private void Customers_ColumnChanging(object sender, System.Data.DataColumnChangeEventArgs e) {
    
       //Only check for errors in the Product column
       if (e.Column.ColumnName.Equals("Product")) {
    
          //Do not allow "Automobile" as a product
          if (e.ProposedValue.Equals("Automobile")) {
             object badValue = e.ProposedValue;
             e.ProposedValue = "Bad Data";
             e.Row.RowError = "The Product column contains an error";
             e.Row.SetColumnError(e.Column, "Product cannot be " + badValue);
          }
       }
    }
    
  2. 이벤트 처리기를 이벤트에 연결합니다.

    양식의 Load 이벤트 또는 해당 생성자 내에 다음 코드를 배치합니다.

    ' Assumes the grid is bound to a dataset called customersDataSet1
    ' with a table called Customers.
    ' Put this code in the form's Load event or its constructor.
    AddHandler customersDataSet1.Tables("Customers").ColumnChanging, AddressOf Customers_ColumnChanging
    
    // Assumes the grid is bound to a dataset called customersDataSet1
    // with a table called Customers.
    // Put this code in the form's Load event or its constructor.
    customersDataSet1.Tables["Customers"].ColumnChanging += new DataColumnChangeEventHandler(this.Customers_ColumnChanging);
    

참고하십시오