방법: Smartphone에서 DataGrid 사용
업데이트: 2007년 11월
Smartphone 연락처 프로그램과 비슷한 Smartphone 응용 프로그램을 만들 수 있습니다.
![]() |
---|
.NET Compact Framework 3.5 이전 버전을 사용하는 경우 DataGrid를 사용하려면 프로젝트에 System.Windows.Forms.DataGrid.dll에 대한 참조를 추가해야 합니다. |
이 예제에서는 DataGrid 컨트롤에 Northwind 데이터베이스의 제품 이름 목록을 표시하는 기본 폼을 보여 줍니다. Northwind 데이터베이스는 Visual Studio와 함께 설치됩니다. 또한 이 예제에는 현재 레코드를 표시하는 요약 뷰 폼과 데이터를 편집하고 새 레코드를 추가하는 편집 뷰 폼이 포함되어 있습니다. BindingSource 개체는 데이터베이스에서 현재 선택된 레코드에 대한 액세스를 제공합니다. 데이터 바인딩 컨트롤 외에도 BindingSource 개체는 현재 행의 DataRowView 개체를 반환할 수 있습니다. DataRowView를 사용하여 열의 현재 값을 확인하는 등 여러 가지 목적으로 데이터에 액세스할 수 있습니다.
또는 DataGrid 컨트롤의 스마트 태그에 대한 바로 가기 메뉴에서 데이터 폼 생성을 선택하여 Visual Studio가 요약 및 편집 폼을 자동으로 생성하도록 할 수 있습니다. 요약 및 편집 폼에 대한 이 예제에서는 데모용으로 두 개의 열만 사용합니다.
이 응용 프로그램에는 다음 표에 설명된 폼이 있습니다. 이 표에는 또한 Smartphone의 왼쪽 및 오른쪽 소프트 키에 대한 해당 메뉴 옵션도 나열되어 있습니다.
폼 |
기능 |
왼쪽 소프트 키 |
오른쪽 소프트 키 |
---|---|---|---|
기본 폼 (Form1) |
DataGrid 컨트롤에서 테이블의 한 열을 Smartphone 연락처 목록 스타일로 표시합니다. 작업 키를 누르거나 에뮬레이터를 사용하는 키보드에서 Enter 키를 누르면 요약 뷰 폼이 표시됩니다. |
New 데이터베이스에 새 레코드를 추가하고 EditView 폼을 표시합니다. |
Edit EditView 폼을 표시합니다. |
SummaryView |
보기 편하도록 최적화하여 현재 레코드의 열 값을 표시합니다. |
Done 기본 폼으로 돌아갑니다. |
(없음) |
EditView |
편집하기 편하도록 최적화하여 현재 레코드의 열 값을 표시합니다. |
Done 대화 상자에서 확인을 눌러 데이터베이스를 업데이트한 다음 기본 폼을 표시합니다. |
Cancel 대화 상자를 취소하고 기본 폼을 표시합니다. |
프로젝트를 만들고 기본 폼을 디자인하려면
Visual Studio에서 스마트 장치 프로젝트를 만들고 대상 플랫폼을 Windows Mobile 5.0 for Smartphone SDK 또는 Windows Mobile 6 Standard SDK로 설정합니다.
데이터 메뉴에서 새 데이터 소스 추가를 클릭합니다.
데이터 소스 구성 마법사에서 Microsoft SQL Server Compact Edition(.NET Framework Data Provider for SQL Server CE)을 사용하여 Northwind 데이터베이스에 연결합니다. Northwind 데이터베이스인 Northwind.sdf는 \Program Files\Microsoft SQL Server Compact Edition\v3.5\Samples 폴더에 설치되어 있습니다.
참고:
Windows Vista에서 Northwind 데이터베이스에 액세스하려면 관리자로 Visual Studio를 실행해야 합니다. 데이터베이스를 추가하는 방법에 대한 자세한 내용은 방법: 장치 프로젝트에 데이터베이스 추가를 참조하십시오.
마법사의 데이터베이스 개체 선택 페이지에서 Products 테이블과 이 테이블의 모든 열을 선택합니다.
도구 상자에서 DataGrid 컨트롤을 폼에 추가합니다.
DataGrid 컨트롤이 Smartphone의 연락처 목록처럼 나타나도록 하려면 해당 속성을 다음 표와 같이 설정합니다.
DataGrid 속성
설정 값
False
False
X는 -2, y는 -2인 Point 구조체
너비가 184, 높이가 190인 Size 구조체
DataSource 속성을 Orders 테이블로 설정합니다. Visual Studio에서 프로젝트에 NorthwindDataSet, ProductsBindingSource 및 ProductsTableAdapter 개체를 추가합니다.
속성 창에서 TableStyles 속성을 클릭합니다. 이 작업으로 DataGridTableStyle 컬렉션 편집기 대화 상자가 표시됩니다. 그런 후 다음 작업을 수행합니다.
TableStyles 컬렉션에 DataGridTableStyle 개체를 추가합니다.
MappingName 속성으로 "Products"를 지정합니다.
GridColumnStyle 속성을 클릭합니다. 이 작업으로 DataGridColumnStyle 컬렉션 편집기 대화 상자가 표시됩니다.
GridColumnStyles 컬렉션에 DataGridTextBoxColumn 개체를 추가합니다.
MappingName 속성을 클릭하고 Product Name을 선택합니다.
원하는 머리글 텍스트와 너비를 설정합니다.
추가 열에 대해 반복합니다.
대화 상자를 닫습니다.
각각 요약 뷰와 편집 뷰로 사용할 두 개의 폼을 프로젝트에 추가합니다. 각각의 이름을 SummaryView와 EditView로 지정합니다.
SummaryView 및 EditView 폼의 생성자에 BindingSource 개체를 가져오는 매개 변수를 추가합니다. 이러한 폼에서 CurrentBindingSouce라는 전역 변수를 선언하여 생성자에 전달된 BindingSource 개체로 설정합니다. 이것은 InitializeComponent 메서드가 호출되기 전에 설정되어야 합니다.
Visual Basic 개발자는 코드 창의 오른쪽 위에 있는 메서드 이름 목록에서 New 메서드를 추가하여 폼에 Sub New를 추가해야 합니다.
Dim CurrentBindingSource As BindingSource Public Sub New(ByVal bsource As BindingSource) CurrentBindingSource = bsource InitializeComponent() End Sub
private BindingSource CurrentBindingSource; public SummaryView(BindingSource bsource) { CurrentBindingSource = bsource; InitializeComponent(); }
기본 폼에서 New라는 MenuItem 개체(MenuItem1)와 Edit라는 다른 개체(MenuItem2)를 추가합니다. 이러한 메뉴는 Smartphone의 왼쪽과 오른쪽 소프트 키에 해당합니다. New 및 Edit의 Click 이벤트에 대해 다음 코드를 추가합니다.
' Add new record. Private Sub MenuItem1_Click(ByVal sender As System.Object, _ ByVal e As System.EventArgs) Handles MenuItem1.Click ProductsBindingSource.AddNew() Dim EditViewDialog As New EditView(ProductsBindingSource) If EditViewDialog.ShowDialog() <> DialogResult.OK Then ProductsBindingSource.CancelEdit() Else ProductsBindingSource.EndEdit() ProductsTableAdapter.Update(Me.NorthwindDataSet) End If End Sub ' Edit record. Private Sub MenuItem2_Click(ByVal sender As System.Object, _ ByVal e As System.EventArgs) Handles MenuItem1.Click Dim EditViewDialog As New EditView(ProductsBindingSource) If EditViewDialog.ShowDialog() <> DialogResult.OK Then ProductsBindingSource.CancelEdit() Else ProductsBindingSource.EndEdit() ProductsTableAdapter.Update(Me.NorthwindDataSet) End If End Sub
// Add new record. private void menuItem1_Click(object sender, EventArgs e) { productsBindingSource.AllowNew = true; productsBindingSource.AddNew(); EditView EditViewDialog = new EditView(productsBindingSource); if (EditViewDialog.ShowDialog() != DialogResult.OK) { productsBindingSource.CancelEdit(); } else { ProductsBindingSource.EndEdit(); this.productsTableAdapter.Update(this.northwindDataSet); } } // Edit record (Edit). private void menuItem2_Click(object sender, EventArgs e) { EditView EditViewDialog = new EditView(productsBindingSource); if (EditViewDialog.ShowDialog() != DialogResult.OK) { productsBindingSource.CancelEdit(); } else { productsBindingSource.EndEdit(); this.productsTableAdapter.Update(this.northwindDataSet); } }
기본 폼에서, Smartphone의 작업 키를 누를 때 발생하는 KeyDown 이벤트에 대한 코드를 추가합니다. 이 작업으로 SummaryView 폼이 표시됩니다.
Private Sub DataGrid1_KeyDown(ByVal sender As System.Object, _ ByVal e As System.Windows.Forms.KeyEventArgs) _ Handles DataGrid1.KeyDown If (e.KeyCode = Keys.Enter) Then Dim SummaryViewDialog As SummaryView = New SummaryView(ProductsBindingSource) Cursor.Current = Cursors.Default SummaryView.ShowDialog() End If End Sub
private void dataGrid1_KeyDown(object sender, KeyEventArgs e) { if (e.KeyCode == Keys.Enter) { SummaryView SummaryViewDialog = new SummaryView(productsBindingSource); SummaryViewDialog.ShowDialog(); } }
요약 뷰를 만들려면
폼에 다음 컨트롤을 추가합니다.
SummaryView 폼에 대한 생성자에 다음 코드를 추가하여 데이터 바인딩을 설정합니다. CurrentBindingSource라는 폼 변수를 선언하여 폼의 생성자에서 전달된 BindingSource 인스턴스로 설정되도록 합니다. DataRowView 개체는 Discontinued 열이 true이고 Discontinued 레이블이 표시되는지 여부를 결정합니다.
Public Sub New(ByVal bsource As BindingSource) CurrentBindingSource = bsource ' This call is required by the Windows Forms Designer. InitializeComponent() ' Bind the label that shows the product name. ProductNameLabelVal.DataBindings.Add("Text", _ CurrentBindingSource, "Product Name") ' Show the Discontinued label if ' that value is true in the database. Dim drView As DataRowView drView = CurrentBindingSource.Current If drView.Item("Discontinued") = True Then DiscontinuedLabel.Visible = True Else DiscontinuedLabel.Visible = False End If End Sub
private BindingSource CurrentBindingSource; public SummaryView(BindingSource bsource) { CurrentBindingSource = bsource; InitializeComponent(); // Bind the label that shows the product name. ProductNameLabelVal.DataBindings.Add("Text", CurrentBindingSource, "Product Name"); // Show the Discontinued label if // that value is true in the database. DataRowView drView; drView = (DataRowView) CurrentBindingSource.Current; if (drView["Discontinued"] == true) { DiscontinuedLabel.Visible = true; } else { DiscontinuedLabel.Visible = false; } }
왼쪽 소프트 키에 대해 Done이라는 MenuItem 개체를 추가하여 폼을 닫고 기본 폼으로 돌아갑니다.
Private Sub MenuItem1_Click(ByVal sender As System.Object, _ ByVal e As System.EventArgs) Handles MenuItem1.Click Me.Close End Sub
private void MenuItem1_Click(object sender, System.EventArgs e) { this.Close(); }
편집 뷰를 만들려면
Microsoft.WindowsCE.Forms 네임스페이스에 대한 참조를 프로젝트에 추가합니다. 이것은 텍스트 상자 컨트롤에서 Smartphone InputMode를 설정하는 데 필요합니다.
폼에 다음 컨트롤을 추가합니다.
데이터 바인딩을 설정하려면 폼의 생성자에서 InitializeComponent 호출 뒤에 다음 코드를 추가합니다. 이 코드는 새 레코드를 추가하거나 기존 레코드를 편집하는 작업을 수행합니다. 새 레코드가 추가되는 경우 DataRowView 개체는 Discontinued 열이 null 값을 갖는지 여부를 확인합니다. 값이 null이면 확인란이 false로 설정됩니다.
Public Sub New(ByVal bsource As BindingSource) CurrentBindingSource = bsource ' This call is required by the Windows Forms Designer. InitializeComponent() ' Add any initialization after the InitializeComponent() call. ' Set the Smartphone input mode. InputModeEditor.SetInputMode(ProductNameTextBox,_ InputMode.AlphaT9) ProductNameTextBox.DataBindings.Add("Text",_ CurrentBindingSource, "Product Name") ' Determine the Discontinued value. ' If null, change to False. Dim drView As DataRowView drView = CurrentBindingSource.Current ' Set the bindings. If IsDBNull(drView("Discontinued")) Then DiscontinuedCheckBox.DataBindings.Add("CheckState",_ CurrentBindingSource, "Discontinued", True,_ DataSourceUpdateMode.OnValidation, False, "") Else DiscontinuedCheckBox.DataBindings.Add("Checked",_ CurrentBindingSource, "Discontinued") End If End Sub
public EditView(BindingSource bsource) { CurrentBindingSource = bsource; InitializeComponent(); // Set the Smartphone input mode. InputModeEditor.SetInputMode(ProductNameTextBox, InputMode.AlphaT9); // Set the bindings. ProductNameTextBox.DataBindings.Add("Text", CurrentBindingSource,"Product Name"); // Determine the Discontinued value. // If null, change to False. DataRowView drView; drView = (DataRowView) CurrentBindingSource.Current; if(drView("Discontinued")== null) { DiscontinuedCheckBox.DataBindings.Add("CheckState", CurrentBindingSource, "Discontinued", true,DataSourceUpdateMode.OnValidation,false,""); } else { DiscontinuedCheckBox.DataBindings.Add("Checked", CurrentBindingSource, "Discontinued"); } }
왼쪽 소프트 키에 대해 Done이라는 MenuItem 개체를 추가하여 데이터베이스를 변경 내용으로 업데이트하고 기본 폼으로 돌아갑니다.
Private Sub MenuItem1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MenuItem1.Click Me.DialogResult = DialogResult.OK Me.Close() End Sub
Private void MenuItem1_Click(object sender, System.EventArgs e) { this.DialogResult = DialogResult.OK; this.Close(); }
오른쪽 소프트 키에 대해 Cancel이라는 MenuItem 개체를 추가하여 변경 내용을 취소하고 기본 폼으로 돌아갑니다.
Private Sub MenuItem2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MenuItem1.Click Me.DialogResult = DialogResult.Cancel Me.Close() End Sub
Private void MenuItem2_Click(object sender, System.EventArgs e) { this.DialogResult = DialogResult.Cancel; this.Close(); }
코드 컴파일
이 예제에는 다음과 같은 네임스페이스에 대한 참조가 필요합니다.