Бөлісу құралы:


ConvertEventArgs Класс

Определение

Предоставляет данные для событий Format и Parse.

public ref class ConvertEventArgs : EventArgs
public class ConvertEventArgs : EventArgs
type ConvertEventArgs = class
    inherit EventArgs
Public Class ConvertEventArgs
Inherits EventArgs
Наследование
ConvertEventArgs
Производный

Примеры

В следующем примере кода создается Bindingделегат, добавляет ConvertEventHandler делегат как в Parse события, так и Format используется DataBindings свойство для добавления BindingBindingsCollectionTextBox элемента управления. Делегат DecimalToCurrencyString события, добавляемый в Format событие, использует ToString метод для форматирования привязанного значения ( Decimal типа) в виде валюты. Делегат CurrencyStringToDecimal события, добавляемый в Parse событие, преобразует значение, отображаемое элементом управления обратно в Decimal тип.

private:
   void DecimalToCurrencyString( Object^ /*sender*/, ConvertEventArgs^ cevent )
   {
      // The method converts only to string type. Test this using the DesiredType.
      if ( cevent->DesiredType != String::typeid )
      {
         return;
      }
      
      // Use the ToString method to format the value as currency ("c").
      cevent->Value = ( (Decimal^)(cevent->Value) )->ToString( "c" );
   }

   void CurrencyStringToDecimal( Object^ /*sender*/, ConvertEventArgs^ cevent )
   {
      // The method converts back to decimal type only. 
      if ( cevent->DesiredType != Decimal::typeid )
      {
         return;
      }
      
      // Converts the string back to decimal using the static Parse method.
      cevent->Value = Decimal::Parse( cevent->Value->ToString(),
         NumberStyles::Currency, nullptr );
   }

   void BindControl()
   {
      // Creates the binding first. The OrderAmount is typed as Decimal.
      Binding^ b = gcnew Binding(
         "Text",ds,"customers.custToOrders.OrderAmount" );
      
      // Adds the delegates to the events.
      b->Format += gcnew ConvertEventHandler(
         this, &Form1::DecimalToCurrencyString );
      b->Parse += gcnew ConvertEventHandler(
         this, &Form1::CurrencyStringToDecimal );
      text1->DataBindings->Add( b );
   }
private void DecimalToCurrencyString(object sender, ConvertEventArgs cevent)
{
   // The method converts only to string type. Test this using the DesiredType.
   if(cevent.DesiredType != typeof(string)) return;

   // Use the ToString method to format the value as currency ("c").
   cevent.Value = ((decimal) cevent.Value).ToString("c");
}

private void CurrencyStringToDecimal(object sender, ConvertEventArgs cevent)
{
   // The method converts back to decimal type only. 
   if(cevent.DesiredType != typeof(decimal)) return;

   // Converts the string back to decimal using the static Parse method.
   cevent.Value = Decimal.Parse(cevent.Value.ToString(),
   NumberStyles.Currency, null);
}

private void BindControl()
{
   // Creates the binding first. The OrderAmount is typed as Decimal.
   Binding b = new Binding
   ("Text", ds, "customers.custToOrders.OrderAmount");
   // Adds the delegates to the events.
   b.Format += new ConvertEventHandler(DecimalToCurrencyString);
   b.Parse += new ConvertEventHandler(CurrencyStringToDecimal);
   text1.DataBindings.Add(b);
}
Private Sub DecimalToCurrencyString(sender As Object, cevent As ConvertEventArgs)
   ' The method converts only to string type. Test this using the DesiredType.
   If Not cevent.DesiredType Is GetType(String) Then
      Return
   End If 
   ' Use the ToString method to format the value as currency ("c").
   cevent.Value = CDec(cevent.Value).ToString("c")
End Sub
 
 
Private Sub CurrencyStringToDecimal(sender As Object, cevent As ConvertEventArgs)
   ' The method converts back to decimal type only. 
   If Not cevent.DesiredType Is GetType(Decimal) Then
      Return
   End If 
   ' Converts the string back to decimal using the shared Parse method.
   cevent.Value = Decimal.Parse(cevent.Value.ToString, _
   NumberStyles.Currency, nothing)

End Sub
 
 
Private Sub BindControl()
   ' Creates the binding first. The OrderAmount is typed as Decimal.
   Dim b As New Binding("Text", ds, "customers.custToOrders.OrderAmount")
   ' Adds the delegates to the events.
   AddHandler b.Format, AddressOf DecimalToCurrencyString
   AddHandler b.Parse, AddressOf CurrencyStringToDecimal
   text1.DataBindings.Add(b)
End Sub

Комментарии

Используется ConvertEventArgs для форматирования и неформатации значений Binding , отображаемых элементом управления Windows Forms, привязанным к данным через объект. Событие Format происходит всякий раз, когда свойство элемента управления привязано к значению, и Parse событие происходит всякий раз, когда изменяется привязанное значение.

Parse События Format позволяют создавать настраиваемые форматы для отображения данных. Например, если данные в таблице имеют тип Decimal, можно указать, что данные должны отображаться в формате локальной валюты, задав Value свойство ConvertEventArgs отформатированного значения в событии Format . Следовательно, необходимо отменить формат отображаемого значения в событии Parse .

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

Конструкторы

Имя Описание
ConvertEventArgs(Object, Type)

Инициализирует новый экземпляр класса ConvertEventArgs.

Свойства

Имя Описание
DesiredType

Возвращает тип данных требуемого значения.

Value

Возвращает или задает значение ConvertEventArgsобъекта .

Методы

Имя Описание
Equals(Object)

Определяет, равен ли указанный объект текущему объекту.

(Унаследовано от Object)
GetHashCode()

Служит хэш-функцией по умолчанию.

(Унаследовано от Object)
GetType()

Возвращает Type текущего экземпляра.

(Унаследовано от Object)
MemberwiseClone()

Создает неглубокую копию текущей Object.

(Унаследовано от Object)
ToString()

Возвращает строку, представляющую текущий объект.

(Унаследовано от Object)

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

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