Поделиться через


ListView.AfterLabelEdit Событие

Определение

Происходит, когда метка для элемента редактируется пользователем.

public:
 event System::Windows::Forms::LabelEditEventHandler ^ AfterLabelEdit;
public event System.Windows.Forms.LabelEditEventHandler AfterLabelEdit;
public event System.Windows.Forms.LabelEditEventHandler? AfterLabelEdit;
member this.AfterLabelEdit : System.Windows.Forms.LabelEditEventHandler 
Public Custom Event AfterLabelEdit As LabelEditEventHandler 

Тип события

Примеры

В следующем примере кода показано, как использовать AfterLabelEdit событие для ограничения недавно измененной метки символами в алфавите. В примере используется ASCIIEncoding класс для получения кода символов ASCII каждого символа новой метки. Если символ падает между кодами ASCII, представляющими числа, новая метка не может быть применена к элементу. В этом примере требуется, чтобы вы создали ListView элемент управления в форме и добавили в него элементы. В примере также требуется, чтобы событие было подключено AfterLabelEdit к обработчику событий, определенному в примере кода. Чтобы использовать ASCIIEncoding класс, файл должен включать System.Text пространство имен.

private:
   void MyListView_AfterLabelEdit( Object^ /*sender*/, System::Windows::Forms::LabelEditEventArgs^ e )
   {
      // Determine if label is changed by checking for 0.
      if ( e->Label == nullptr )
               return;

      // ASCIIEncoding is used to determine if a number character has been entered.
      ASCIIEncoding^ AE = gcnew ASCIIEncoding;

      // Convert the new label to a character array.
      array<Char>^temp = e->Label->ToCharArray();

      // Check each character in the new label to determine if it is a number.
      for ( int x = 0; x < temp->Length; x++ )
      {
         // Encode the character from the character array to its ASCII code.
         array<Byte>^bc = AE->GetBytes( temp[ x ].ToString() );

         // Determine if the ASCII code is within the valid range of numerical values.
         if ( bc[ 0 ] > 47 && bc[ 0 ] < 58 )
         {
            // Cancel the event and return the lable to its original state.
            e->CancelEdit = true;

            // Display a MessageBox alerting the user that numbers are not allowed.
            MessageBox::Show( "The text for the item cannot contain numerical values." );

            // Break out of the loop and exit.
            return;
         }
      }
   }
private void MyListView_AfterLabelEdit(object sender, System.Windows.Forms.LabelEditEventArgs e)
{
 
   // Determine if label is changed by checking for null.
   if (e.Label == null)
      return;

   // ASCIIEncoding is used to determine if a number character has been entered.
   ASCIIEncoding AE = new ASCIIEncoding();
   // Convert the new label to a character array.
   char[] temp = e.Label.ToCharArray();

   // Check each character in the new label to determine if it is a number.
   for(int x=0; x < temp.Length; x++)
   {
      // Encode the character from the character array to its ASCII code.
      byte[] bc = AE.GetBytes(temp[x].ToString());
   
      // Determine if the ASCII code is within the valid range of numerical values.
      if(bc[0] > 47 && bc[0] < 58)
      {
         // Cancel the event and return the lable to its original state.
         e.CancelEdit = true;
         // Display a MessageBox alerting the user that numbers are not allowed.
         MessageBox.Show ("The text for the item cannot contain numerical values.");
         // Break out of the loop and exit.
         return;
      }
   }
}
Private Sub MyListView_AfterLabelEdit(ByVal sender As Object, ByVal e As System.Windows.Forms.LabelEditEventArgs) Handles listView1.AfterLabelEdit

   ' Determine if label is changed by checking to see if it is equal to Nothing.
   If e.Label Is Nothing Then
      Return
   End If
   ' ASCIIEncoding is used to determine if a number character has been entered.
   Dim AE As New ASCIIEncoding()
   ' Convert the new label to a character array.
   Dim temp As Char() = e.Label.ToCharArray()

   ' Check each character in the new label to determine if it is a number.
   Dim x As Integer
   For x = 0 To temp.Length - 1
      ' Encode the character from the character array to its ASCII code.
      Dim bc As Byte() = AE.GetBytes(temp(x).ToString())

      ' Determine if the ASCII code is within the valid range of numerical values.
      If bc(0) > 47 And bc(0) < 58 Then
         ' Cancel the event and return the lable to its original state.
         e.CancelEdit = True
         ' Display a MessageBox alerting the user that numbers are not allowed.
         MessageBox.Show("The text for the item cannot contain numerical values.")
         ' Break out of the loop and exit.
         Return
      End If
   Next x
End Sub

Комментарии

Событие AfterLabelEdit возникает, когда пользователь завершает изменение текста для элемента. Новая строка, которую пользователь вводит для элемента, передается в событие, и обработчик событий может отклонить изменение. Если обработчик событий отклоняет изменение, текст возвращается к тексту, так как он был до того, как пользователь начал редактировать элемент.

Замечание

ListView.AfterLabelEdit Так как событие происходит до фиксации изменения метки, вызов ListView.Sort метода в обработчике для этого события будет сортировать элемент с использованием исходного значения.

AfterLabelEdit Чтобы событие было поднято, LabelEditListView свойство элемента управления должно иметь значение true.

Вы можете создать обработчик событий для события, BeforeLabelEdit чтобы выполнить задачи, прежде чем пользователь изменяет текст элемента.

Дополнительные сведения об обработке событий см. в разделе "Обработка и создание событий".

Применяется к

См. также раздел