DataGridViewCell.ErrorText Propriedade
Definição
Importante
Algumas informações se referem a produtos de pré-lançamento que podem ser substancialmente modificados antes do lançamento. A Microsoft não oferece garantias, expressas ou implícitas, das informações aqui fornecidas.
Obtém ou define o texto que descreve uma condição de erro associada à célula.
public:
property System::String ^ ErrorText { System::String ^ get(); void set(System::String ^ value); };
[System.ComponentModel.Browsable(false)]
public string ErrorText { get; set; }
[<System.ComponentModel.Browsable(false)>]
member this.ErrorText : string with get, set
Public Property ErrorText As String
Valor da propriedade
O texto que descreve uma condição de erro associada à célula.
- Atributos
Exemplos
O exemplo de código a seguir demonstra como usar essa propriedade ao lidar com condições de erro em um não associado DataGridView. O AnnotateCell
método define uma cadeia de caracteres de mensagem de erro para a ErrorText propriedade .
void dataGridView1_CellValidating( Object^ /*sender*/, DataGridViewCellValidatingEventArgs^ newValue )
{
DataGridViewColumn^ column = dataGridView1->Columns[ newValue->ColumnIndex ];
if ( column->Name->Equals( "Track" ) )
{
CheckTrack( newValue );
}
else
if ( column->Name->Equals( "Release Date" ) )
{
CheckDate( newValue );
}
}
void CheckTrack( DataGridViewCellValidatingEventArgs^ newValue )
{
Int32 ignored;
if ( newValue->FormattedValue->ToString() == String::Empty )
{
NotifyUserAndForceRedo( "Please enter a track", newValue );
}
else
if ( !Int32::TryParse( newValue->FormattedValue->ToString(), ignored ) )
{
NotifyUserAndForceRedo( "A Track must be a number", newValue );
}
else
if ( Int32::Parse( newValue->FormattedValue->ToString() ) < 1 )
{
NotifyUserAndForceRedo( "Not a valid track", newValue );
editedLastColumn = true;
}
}
void NotifyUserAndForceRedo( String^ errorMessage, DataGridViewCellValidatingEventArgs^ newValue )
{
MessageBox::Show( errorMessage );
newValue->Cancel = true;
}
void CheckDate( DataGridViewCellValidatingEventArgs^ newValue )
{
try
{
DateTime::Parse( newValue->FormattedValue->ToString() ).ToLongDateString();
AnnotateCell( String::Empty, newValue );
}
catch ( FormatException^ /*ex*/ )
{
AnnotateCell( "You did not enter a valid date.", newValue );
}
}
void AnnotateCell( String^ errorMessage, DataGridViewCellValidatingEventArgs^ editEvent )
{
DataGridViewCell^ cell = dataGridView1->Rows[ editEvent->RowIndex ]->Cells[ editEvent->ColumnIndex ];
cell->ErrorText = errorMessage;
}
private void dataGridView1_CellValidating(object sender, DataGridViewCellValidatingEventArgs e)
{
DataGridViewColumn column = dataGridView1.Columns[e.ColumnIndex];
if (column.Name == "Track")
{
CheckTrack(e);
}
else if (column.Name == "Release Date")
{
CheckDate(e);
}
}
private static void CheckTrack(DataGridViewCellValidatingEventArgs newValue)
{
Int32 ignored = new Int32();
if (String.IsNullOrEmpty(newValue.FormattedValue.ToString()))
{
NotifyUserAndForceRedo("Please enter a track", newValue);
}
else if (!Int32.TryParse(newValue.FormattedValue.ToString(), out ignored))
{
NotifyUserAndForceRedo("A Track must be a number", newValue);
}
else if (Int32.Parse(newValue.FormattedValue.ToString()) < 1)
{
NotifyUserAndForceRedo("Not a valid track", newValue);
}
}
private static void NotifyUserAndForceRedo(string errorMessage, DataGridViewCellValidatingEventArgs newValue)
{
MessageBox.Show(errorMessage);
newValue.Cancel = true;
}
private void CheckDate(DataGridViewCellValidatingEventArgs newValue)
{
try
{
DateTime.Parse(newValue.FormattedValue.ToString()).ToLongDateString();
AnnotateCell(String.Empty, newValue);
}
catch (FormatException)
{
AnnotateCell("You did not enter a valid date.", newValue);
}
}
private void AnnotateCell(string errorMessage, DataGridViewCellValidatingEventArgs editEvent)
{
DataGridViewCell cell = dataGridView1.Rows[editEvent.RowIndex].Cells[editEvent.ColumnIndex];
cell.ErrorText = errorMessage;
}
Private Sub dataGridView1_CellValidating(ByVal sender As Object, _
ByVal e As _
DataGridViewCellValidatingEventArgs) _
Handles dataGridView1.CellValidating
Dim column As DataGridViewColumn = _
dataGridView1.Columns(e.ColumnIndex)
If column.Name = "Track" Then
CheckTrack(e)
ElseIf column.Name = "Release Date" Then
CheckDate(e)
End If
End Sub
Private Shared Sub CheckTrack(ByVal newValue As DataGridViewCellValidatingEventArgs)
If String.IsNullOrEmpty(newValue.FormattedValue.ToString()) Then
NotifyUserAndForceRedo("Please enter a track", newValue)
ElseIf Not Integer.TryParse( _
newValue.FormattedValue.ToString(), New Integer()) Then
NotifyUserAndForceRedo("A Track must be a number", newValue)
ElseIf Integer.Parse(newValue.FormattedValue.ToString()) < 1 Then
NotifyUserAndForceRedo("Not a valid track", newValue)
End If
End Sub
Private Shared Sub NotifyUserAndForceRedo(ByVal errorMessage As String, ByVal newValue As DataGridViewCellValidatingEventArgs)
MessageBox.Show(errorMessage)
newValue.Cancel = True
End Sub
Private Sub CheckDate(ByVal newValue As DataGridViewCellValidatingEventArgs)
Try
DateTime.Parse(newValue.FormattedValue.ToString()).ToLongDateString()
AnnotateCell(String.Empty, newValue)
Catch ex As FormatException
AnnotateCell("You did not enter a valid date.", newValue)
End Try
End Sub
Private Sub AnnotateCell(ByVal errorMessage As String, _
ByVal editEvent As DataGridViewCellValidatingEventArgs)
Dim cell As DataGridViewCell = _
dataGridView1.Rows(editEvent.RowIndex).Cells( _
editEvent.ColumnIndex)
cell.ErrorText = errorMessage
End Sub
Comentários
Normalmente, a ErrorText propriedade é usada ao manipular o CellValidating evento do DataGridView. Se o valor da célula falhar em alguns critérios de validação, defina a ErrorText propriedade e cancele a operação de confirmação definindo a Cancel propriedade de DataGridViewCellValidatingEventArgs como true
. O texto especificado é exibido pelo DataGridViewe o usuário é solicitado a corrigir o erro nos dados da célula.
Quando a VirtualMode propriedade do DataGridView é true
, você pode fornecer texto de erro para linhas e células usando os RowErrorTextNeeded eventos e CellErrorTextNeeded .
Quando você atribui uma cadeia de caracteres diferente ErrorText a uma célula, o CellErrorTextChanged evento do DataGridView controle é gerado.
A partir do .NET Framework 4.5.2, o redimensionamento do ícone de erro é determinado pela configuração de DPI do sistema quando o arquivo app.config contém a seguinte entrada:
<appSettings>
<add key="EnableWindowsFormsHighDpiAutoResizing" value="true" />
</appSettings>