방법: DBNull 데이터베이스 값에 Windows Forms 컨트롤 바인딩

Windows Forms 컨트롤을 데이터 소스에 바인딩하고 데이터 소스에서 DBNull 값이 반환되면 이벤트를 처리하거나 서식을 지정하거나 구문을 분석하지 않고도 적절한 값을 대체할 수 있습니다. NullValue 속성은 데이터 소스 값에 서식을 지정하거나 구문을 분석할 때 DBNull을 지정한 개체로 변환합니다.

예제

다음 예제에서는 두 가지 경우에서 DBNull 값을 바인딩하는 방법을 보여 줍니다. 첫 번째 경우에는 문자열 속성에 대해 NullValue를 설정하는 방법을 보여 주고, 두 번째 경우에는 이미지 속성에 대해 NullValue를 설정하는 방법을 보여 줍니다.

Imports System
Imports System.Collections.Generic
Imports System.ComponentModel
Imports System.Data
Imports System.Drawing
Imports System.Text
Imports System.Data.SqlClient
Imports System.Windows.Forms



Public Class Form1
    Inherits Form

    Public Sub New() 
    End Sub

    ' The controls and components we need for the form.
    Private WithEvents button1 As Button
    Private pictureBox1 As PictureBox
    Private bindingSource1 As BindingSource
    Private textBox1 As TextBox
    Private textBox2 As TextBox

    ' Data table to hold the database data.
    Private employeeTable As New DataTable()


    Private Sub Form1_Load(ByVal sender As Object, ByVal e As EventArgs) _
        Handles Me.Load

        ' Basic form setup.
        Me.pictureBox1 = New PictureBox()
        Me.bindingSource1 = New BindingSource()
        Me.textBox1 = New TextBox()
        Me.textBox2 = New TextBox()
        Me.button1 = New Button()
        Me.pictureBox1.Location = New System.Drawing.Point(20, 20)
        Me.pictureBox1.Size = New System.Drawing.Size(174, 179)
        Me.textBox1.Location = New System.Drawing.Point(25, 215)
        Me.textBox1.ReadOnly = True
        Me.textBox2.Location = New System.Drawing.Point(25, 241)
        Me.textBox2.ReadOnly = True
        Me.button1.Location = New System.Drawing.Point(200, 103)
        Me.button1.Text = "Move Next"
        Me.ClientSize = New System.Drawing.Size(292, 273)
        Me.Controls.Add(Me.button1)
        Me.Controls.Add(Me.textBox2)
        Me.Controls.Add(Me.textBox1)
        Me.Controls.Add(Me.pictureBox1)
        Me.ResumeLayout(False)
        Me.PerformLayout()

        ' Create the connection string and populate the data table
        ' with data.
        Dim connectionString As String = "Integrated Security=SSPI;" & _
            "Persist Security Info = False;Initial Catalog=Northwind;" _
            & "Data Source = localhost"
        Dim connection As New SqlConnection()
        connection.ConnectionString = connectionString
        Dim employeeAdapter As New SqlDataAdapter _
            (New SqlCommand("Select * from Employees", connection))
        connection.Open()
        employeeAdapter.Fill(employeeTable)

        ' Set the DataSource property of the BindingSource to the employee table.
        bindingSource1.DataSource = employeeTable

        ' Set up the binding to the ReportsTo column.
        Dim reportsToBinding As Binding = _
            textBox2.DataBindings.Add("Text", bindingSource1, "ReportsTo", _
                True)

        ' Set the NullValue property for this binding.
        reportsToBinding.NullValue = "No Manager"

        ' Set up the binding for the PictureBox using the Add method, setting
        ' the null value in method call.
        pictureBox1.DataBindings.Add("Image", bindingSource1, "Photo", _
            True, DataSourceUpdateMode.Never, _
            New Bitmap(GetType(Button), "Button.bmp"))

        ' Set up the remaining binding.
        textBox1.DataBindings.Add("Text", bindingSource1, "LastName", True)

    End Sub


    ' Move through the data when the button is clicked.
    Private Sub button1_Click(ByVal sender As Object, _
        ByVal e As EventArgs) Handles button1.Click

        bindingSource1.MoveNext()

    End Sub


    <STAThread()>  _
    Shared Sub Main() 
        Application.EnableVisualStyles()
        Application.Run(New Form1())

    End Sub
End Class

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

namespace DBNullCS
{
    public class Form1 : Form
    {
        public Form1()
        {       
            this.Load += new EventHandler(Form1_Load);
        }

        // The controls and components we need for the form.
        private Button button1;
        private PictureBox pictureBox1;
        private BindingSource bindingSource1;
        private TextBox textBox1;
        private TextBox textBox2;

        // Data table to hold the database data.
        DataTable employeeTable = new DataTable();

        void Form1_Load(object sender, EventArgs e)
        {
            // Basic form setup.
            this.pictureBox1 = new PictureBox();
            this.bindingSource1 = new BindingSource();
            this.textBox1 = new TextBox();
            this.textBox2 = new TextBox();
            this.button1 = new Button();
            this.pictureBox1.Location = new System.Drawing.Point(20, 20);
            this.pictureBox1.Size = new System.Drawing.Size(174, 179);
            this.textBox1.Location = new System.Drawing.Point(25, 215);
            this.textBox1.ReadOnly = true;
            this.textBox2.Location = new System.Drawing.Point(25, 241);
            this.textBox2.ReadOnly = true;
            this.button1.Location = new System.Drawing.Point(200, 103);
            this.button1.Text = "Move Next";
            this.button1.Click += new System.EventHandler(this.button1_Click);
            this.ClientSize = new System.Drawing.Size(292, 273);
            this.Controls.Add(this.button1);
            this.Controls.Add(this.textBox2);
            this.Controls.Add(this.textBox1);
            this.Controls.Add(this.pictureBox1);
            this.ResumeLayout(false);
            this.PerformLayout();

            // Create the connection string and populate the data table
            // with data.
            string connectionString = "Integrated Security=SSPI;" +
                "Persist Security Info = False;Initial Catalog=Northwind;" +
                "Data Source = localhost";
            SqlConnection connection = new SqlConnection();
            connection.ConnectionString = connectionString;
            SqlDataAdapter employeeAdapter = 
                new SqlDataAdapter(new SqlCommand("Select * from Employees", connection));
            connection.Open();
            employeeAdapter.Fill(employeeTable);

            // Set the DataSource property of the BindingSource to the employee table.
            bindingSource1.DataSource = employeeTable;

           // Set up the binding to the ReportsTo column.
            Binding reportsToBinding = textBox2.DataBindings.Add("Text", bindingSource1, 
                "ReportsTo", true);

            // Set the NullValue property for this binding.
            reportsToBinding.NullValue = "No Manager";

            // Set up the binding for the PictureBox using the Add method, setting
            // the null value in method call.
            pictureBox1.DataBindings.Add("Image", bindingSource1, "Photo", true, 
                DataSourceUpdateMode.Never, new Bitmap(typeof(Button), "Button.bmp"));

            // Set up the remaining binding.
            textBox1.DataBindings.Add("Text", bindingSource1, "LastName", true);
        }

        // Move through the data when the button is clicked.
        private void button1_Click(object sender, EventArgs e)
        {
            bindingSource1.MoveNext();
        }

        [STAThread]
        static void Main()
        {
            Application.EnableVisualStyles();
            Application.Run(new Form1());
        }

    }
}

바인딩된 속성의 형식과 NullValue 속성의 형식은 같아야 합니다. 그렇지 않으면 오류가 발생하고 NullValue 값이 더 이상 처리되지 않습니다. 이 경우에는 예외가 throw되지 않습니다.

코드 컴파일

이 예제에는 다음 사항이 필요합니다.

  • System, System.Data, System.Drawing 및 System.Windows.Forms 어셈블리에 대한 참조

Visual Basic 또는 Visual C#의 명령줄에서 이 예제를 빌드하는 방법에 대한 자세한 내용은 명령줄에서 빌드(Visual Basic) 또는 csc.exe를 사용한 명령줄 빌드를 참조하십시오. Visual Studio에서 코드를 새 프로젝트에 붙여넣어 이 예제를 빌드할 수도 있습니다. 자세한 내용은 다음을 참조하십시오. 방법: Visual Studio를 사용하여 전체 Windows Forms 코드 예제 컴파일 및 실행방법: Visual Studio를 사용하여 전체 Windows Forms 코드 예제 컴파일 및 실행방법: Visual Studio를 사용하여 전체 Windows Forms 코드 예제 컴파일 및 실행방법: Visual Studio를 사용하여 전체 Windows Forms 코드 예제 컴파일 및 실행방법: Visual Studio를 사용하여 전체 Windows Forms 코드 예제 컴파일 및 실행.

참고 항목

작업

방법: 데이터 바인딩에서 발생하는 오류 및 예외 처리

방법: 형식에 Windows Forms 컨트롤 바인딩

기타 리소스

BindingSource 구성 요소