Como: BIND dados ao controle MaskedTextBox

Você pode BIND dados a um MaskedTextBox controle exatamente sistema autônomo você pode a qualquer Outros controle Windows Forms. No entanto, se o formato dos dados no banco de dados não coincidir com o formato esperado pela sua definição de máscara, você precisará reformatar os dados.O procedimento a seguir demonstra sistema autônomo fazer isso usando o Format e Parse eventos da Binding classe para exibir o número de telefone separado e campos do banco de dados de extensão de telefone sistema autônomo um único campo editável.

O procedimento a seguir requer que você tenha acesso a um banco de dados do SQL servidor com o banco de dados Northwind de exemplo instalado.

Para BIND dados a um controle MaskedTextBox

  1. criar um novo projeto Windows Forms.

  2. arrastar dois TextBox controles para seu formulário; nomeá-los Nome and Sobrenome.

  3. arrastar um MaskedTextBox controle para seu formulário; nome- PhoneMask.

  4. conjunto o Mask propriedade de PhoneMask to (000) 000-0000 x 9999.

  5. Adicione que as seguinte importações de namespace para o formulário.

    using System.Data.SqlClient;
    
    Imports System.Data.SqlClient
    
  6. Clique com o botão direito do mouse na classe e escolha View Code.Colocar esse código em qualquer lugar na sua classe de formulário.

    Binding currentBinding, phoneBinding;
    DataSet employeesTable = new DataSet();
    SqlConnection sc;
    SqlDataAdapter dataConnect;
    
    private void Form1_Load(object sender, EventArgs e)
    {
        DoMaskBinding();
    }
    
    private void DoMaskBinding()
    {
        try
        {
            sc = new SqlConnection("Data Source=CLIENTUE;Initial Catalog=NORTHWIND;Integrated Security=SSPI");
            sc.Open();
        }
        catch (Exception ex)
        {
            MessageBox.Show(ex.Message);
            return;
        }
    
        dataConnect = new SqlDataAdapter("SELECT * FROM Employees", sc);
        dataConnect.Fill(employeesTable, "Employees");
    
        // Now bind MaskedTextBox to appropriate field. Note that we must create the Binding objects
        // before adding them to the control - otherwise, we won't get a Format event on the 
        // initial load. 
        try
        {
            currentBinding = new Binding("Text", employeesTable, "Employees.FirstName");
            firstName.DataBindings.Add(currentBinding);
    
            currentBinding = new Binding("Text", employeesTable, "Employees.LastName");
            lastName.DataBindings.Add(currentBinding);
    
            phoneBinding =new Binding("Text", employeesTable, "Employees.HomePhone");
            // We must add the event handlers before we bind, or the Format event will not get called
            // for the first record.
            phoneBinding.Format += new ConvertEventHandler(phoneBinding_Format);
            phoneBinding.Parse += new ConvertEventHandler(phoneBinding_Parse);
            phoneMask.DataBindings.Add(phoneBinding);
        }
        catch (Exception ex)
        {
            MessageBox.Show(ex.Message);
            return;
        }
    }
    
    Dim WithEvents CurrentBinding, PhoneBinding As Binding
    Dim EmployeesTable As New DataSet()
    Dim sc As SqlConnection
    Dim DataConnect As SqlDataAdapter
    
    Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
        DoMaskedBinding()
    End Sub
    
    Private Sub DoMaskedBinding()
        Try
            sc = New SqlConnection("Data Source=SERVERNAME;Initial Catalog=NORTHWIND;Integrated Security=SSPI")
            sc.Open()
        Catch ex As Exception
            MessageBox.Show(ex.Message)
            Exit Sub
        End Try
    
        DataConnect = New SqlDataAdapter("SELECT * FROM Employees", sc)
        DataConnect.Fill(EmployeesTable, "Employees")
    
        ' Now bind MaskedTextBox to appropriate field. Note that we must create the Binding objects
        ' before adding them to the control - otherwise, we won't get a Format event on the 
        ' initial load.
        Try
            CurrentBinding = New Binding("Text", EmployeesTable, "Employees.FirstName")
            firstName.DataBindings.Add(CurrentBinding)
            CurrentBinding = New Binding("Text", EmployeesTable, "Employees.LastName")
            lastName.DataBindings.Add(CurrentBinding)
            PhoneBinding = New Binding("Text", EmployeesTable, "Employees.HomePhone")
            PhoneMask.DataBindings.Add(PhoneBinding)
        Catch ex As Exception
            MessageBox.Show(ex.Message)
            Application.Exit()
        End Try
    End Sub
    
  7. Adicionar evento manipuladores para o Format e Parse s evento separados e agrupar o Telefone and Extensão campos o limite DataSet.

    private void phoneBinding_Format(Object sender, ConvertEventArgs e)
    {
        String ext;
    
        DataRowView currentRow = (DataRowView)BindingContext[employeesTable, "Employees"].Current;
        if (currentRow["Extension"] == null) 
        {
            ext = "";
        } else 
        {
            ext = currentRow["Extension"].ToString();
        }
    
        e.Value = e.Value.ToString().Trim() + " x" + ext;
    }
    
    private void phoneBinding_Parse(Object sender, ConvertEventArgs e)
    {
        String phoneNumberAndExt = e.Value.ToString();
    
        int extIndex = phoneNumberAndExt.IndexOf("x");
        String ext = phoneNumberAndExt.Substring(extIndex).Trim();
        String phoneNumber = phoneNumberAndExt.Substring(0, extIndex).Trim();
    
        //Get the current binding object, and set the new extension manually. 
        DataRowView currentRow = (DataRowView)BindingContext[employeesTable, "Employees"].Current;
        // Remove the "x" from the extension.
        currentRow["Extension"] = ext.Substring(1);
    
        //Return the phone number.
        e.Value = phoneNumber;
    }
    
    Private Sub PhoneBinding_Format(ByVal sender As Object, ByVal e As ConvertEventArgs) Handles PhoneBinding.Format
        Dim Ext As String
    
        Dim CurrentRow As DataRowView = CType(Me.BindingContext(EmployeesTable, "Employees").Current, DataRowView)
        If (CurrentRow("Extension") Is Nothing) Then
            Ext = ""
        Else
            Ext = CurrentRow("Extension").ToString()
        End If
    
        e.Value = e.Value.ToString().Trim() & " x" & Ext
    End Sub
    
    Private Sub PhoneBinding_Parse(ByVal sender As Object, ByVal e As ConvertEventArgs) Handles PhoneBinding.Parse
        Dim PhoneNumberAndExt As String = e.Value.ToString()
    
        Dim ExtIndex As Integer = PhoneNumberAndExt.IndexOf("x")
        Dim Ext As String = PhoneNumberAndExt.Substring(ExtIndex).Trim()
        Dim PhoneNumber As String = PhoneNumberAndExt.Substring(0, ExtIndex).Trim()
    
        ' Get the current binding object, and set the new extension manually. 
        Dim CurrentRow As DataRowView = CType(Me.BindingContext(EmployeesTable, "Employees").Current, DataRowView)
        ' Remove the "x" from the extension.
        CurrentRow("Extension") = CObj(Ext.Substring(1))
    
        ' Return the phone number.
        e.Value = PhoneNumber
    End Sub
    
  8. Adicionar dois Button controles ao formulário. Nomear o arquivo previousButton and nextButton.clicar duas vezes em cada botão para adicionar um Click evento manipulador e preencherá o evento manipuladores, sistema autônomo neste exemplo de código a seguir.

    private void previousButton_Click(object sender, EventArgs e)
    {
        BindingContext[employeesTable, "Employees"].Position = BindingContext[employeesTable, "Employees"].Position - 1;
    }
    
    private void nextButton_Click(object sender, EventArgs e)
    {
        BindingContext[employeesTable, "Employees"].Position = BindingContext[employeesTable, "Employees"].Position + 1;
    }
    
    Private Sub PreviousButton_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles PreviousButton.Click
        Me.BindingContext(EmployeesTable, "Employees").Position = Me.BindingContext(EmployeesTable, "Employees").Position - 1
    End Sub
    
    Private Sub NextButton_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles NextButton.Click
        Me.BindingContext(EmployeesTable, "Employees").Position = Me.BindingContext(EmployeesTable, "Employees").Position + 1
    End Sub
    
  9. Execute a amostra.edição os dados e usar o Anterior and Próximo botões para ver que os dados são persistidos corretamente à DataSet.

Exemplo

O exemplo de código a seguir é o código completo listando que resulte de concluir o procedimento anterior.

Imports System.Data.SqlClient

Public Class Form1
    Dim WithEvents CurrentBinding, PhoneBinding As Binding
    Dim EmployeesTable As New DataSet()
    Dim sc As SqlConnection
    Dim DataConnect As SqlDataAdapter

    Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
        DoMaskedBinding()
    End Sub

    Private Sub DoMaskedBinding()
        Try
            sc = New SqlConnection("Data Source=localhost;Initial Catalog=NORTHWIND;Integrated Security=SSPI")
            sc.Open()
        Catch ex As Exception
            MessageBox.Show(ex.Message)
            Application.Exit()
        End Try

        DataConnect = New SqlDataAdapter("SELECT * FROM Employees", sc)
        DataConnect.Fill(EmployeesTable, "Employees")

        ' Now bind MaskedTextBox to appropriate field. Note that we must create the Binding objects
        ' before adding them to the control - otherwise, we won't get a Format event on the 
        ' initial load. 
        Try
            CurrentBinding = New Binding("Text", EmployeesTable, "Employees.FirstName")
            firstName.DataBindings.Add(CurrentBinding)
            CurrentBinding = New Binding("Text", EmployeesTable, "Employees.LastName")
            lastName.DataBindings.Add(CurrentBinding)
            PhoneBinding = New Binding("Text", EmployeesTable, "Employees.HomePhone")
            PhoneMask.DataBindings.Add(PhoneBinding)
        Catch ex As Exception
            MessageBox.Show(ex.Message)
            Application.Exit()
        End Try
    End Sub

    Private Sub PhoneBinding_Format(ByVal sender As Object, ByVal e As ConvertEventArgs) Handles PhoneBinding.Format
        Dim Ext As String

        Dim CurrentRow As DataRowView = CType(Me.BindingContext(EmployeesTable, "Employees").Current, DataRowView)
        If (CurrentRow("Extension") Is Nothing) Then
            Ext = ""
        Else
            Ext = CurrentRow("Extension").ToString()
        End If

        e.Value = e.Value.ToString().Trim() & " x" & Ext
    End Sub

    Private Sub PhoneBinding_Parse(ByVal sender As Object, ByVal e As ConvertEventArgs) Handles PhoneBinding.Parse
        Dim PhoneNumberAndExt As String = e.Value.ToString()

        Dim ExtIndex As Integer = PhoneNumberAndExt.IndexOf("x")
        Dim Ext As String = PhoneNumberAndExt.Substring(ExtIndex).Trim()
        Dim PhoneNumber As String = PhoneNumberAndExt.Substring(0, ExtIndex).Trim()

        ' Get the current binding object, and set the new extension manually. 
        Dim CurrentRow As DataRowView = CType(Me.BindingContext(EmployeesTable, "Employees").Current, DataRowView)
        ' Remove the "x" from the extension.
        CurrentRow("Extension") = CObj(Ext.Substring(1))

        ' Return the phone number.
        e.Value = PhoneNumber
    End Sub

    Private Sub NextButton_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles NextButton.Click
        Me.BindingContext(EmployeesTable, "Employees").Position = Me.BindingContext(EmployeesTable, "Employees").Position + 1
    End Sub

    Private Sub PreviousButton_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles PreviousButton.Click
        Me.BindingContext(EmployeesTable, "Employees").Position = Me.BindingContext(EmployeesTable, "Employees").Position - 1
    End Sub
End Class
#region Using directives

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Windows.Forms;
using System.Data.SqlClient;

#endregion

namespace MaskedTextBoxDataCSharp
{
    partial class Form1 : Form
    {
        Binding currentBinding, phoneBinding;
        DataSet employeesTable = new DataSet();
        SqlConnection sc;
        SqlDataAdapter dataConnect;

        public Form1()
        {
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            DoMaskBinding();
        }

        private void DoMaskBinding()
        {
            try
            {
                sc = new SqlConnection("Data Source=localhost;Initial Catalog=NORTHWIND;Integrated Security=SSPI");
                sc.Open();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
                return;
            }

            dataConnect = new SqlDataAdapter("SELECT * FROM Employees", sc);
            dataConnect.Fill(employeesTable, "Employees");


            // Now bind MaskedTextBox to appropriate field. Note that we must create the Binding objects
            // before adding them to the control - otherwise, we won't get a Format event on the 
            // initial load. 
            try
            {
                currentBinding = new Binding("Text", employeesTable, "Employees.FirstName");
                firstName.DataBindings.Add(currentBinding);

                currentBinding = new Binding("Text", employeesTable, "Employees.LastName");
                lastName.DataBindings.Add(currentBinding);

                phoneBinding =new Binding("Text", employeesTable, "Employees.HomePhone");
                // We must add the event handlers before we bind, or the Format event will not get called
                // for the first record.
                phoneBinding.Format += new ConvertEventHandler(phoneBinding_Format);
                phoneBinding.Parse += new ConvertEventHandler(phoneBinding_Parse);
                phoneMask.DataBindings.Add(phoneBinding);
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
                return;
            }
        }

        private void phoneBinding_Format(Object sender, ConvertEventArgs e)
        {
            String ext;

            DataRowView currentRow = (DataRowView)BindingContext[employeesTable, "Employees"].Current;
            if (currentRow["Extension"] == null) 
            {
                ext = "";
            } else 
            {
                ext = currentRow["Extension"].ToString();
            }

            e.Value = e.Value.ToString().Trim() + " x" + ext;
        }

        private void phoneBinding_Parse(Object sender, ConvertEventArgs e)
        {
            String phoneNumberAndExt = e.Value.ToString();

            int extIndex = phoneNumberAndExt.IndexOf("x");
            String ext = phoneNumberAndExt.Substring(extIndex).Trim();
            String phoneNumber = phoneNumberAndExt.Substring(0, extIndex).Trim();

            //Get the current binding object, and set the new extension manually. 
            DataRowView currentRow = (DataRowView)BindingContext[employeesTable, "Employees"].Current;
            // Remove the "x" from the extension.
            currentRow["Extension"] = ext.Substring(1);

            //Return the phone number.
            e.Value = phoneNumber;
        }

        private void previousButton_Click(object sender, EventArgs e)
        {
            BindingContext[employeesTable, "Employees"].Position = BindingContext[employeesTable, "Employees"].Position - 1;
        }

        private void nextButton_Click(object sender, EventArgs e)
        {
            BindingContext[employeesTable, "Employees"].Position = BindingContext[employeesTable, "Employees"].Position + 1;
        }
    }
}

Compilando o código

  • Criar um Visual C# ou Visual Basic projeto.

  • Adicionar o TextBox e MaskedTextBox controles ao formulário, sistema autônomo descrito no procedimento anterior.

  • Abra o arquivo de código fonte para o formulário de padrão do projeto.

  • Substitua o código de fonte desse arquivo com o código listado na seção anterior "Código".

  • compilar o aplicativo.

Consulte também

Tarefas

Demonstra Passo a passo: Trabalhando com o controle MaskedTextBox