HOW TO:在 Pocket PC 上使用 DataGrid

更新:2007 年 11 月

本範例示範幾種技巧,說明如何將 DataGrid 與表單搭配使用,以檢視及編輯 DataGrid 控制項中選取的資料錄,並將新的資料錄加入至資料庫。請注意,您必須提供使用者介面,才能編輯 DataGrid 值,因為 .NET Compact Framework 不支援編輯 DataGrid 儲存格。這個範例會使用隨著 Visual Studio 一起安裝的 Northwind 資料庫。

注意事項:

如果您使用 .NET Compact Framework 2.0 版,則必須在專案中加入 System.Windows.Forms.DataGrid.dll 的參考,才能使用 DataGrid 控制項。

BindingSource 物件提供資料庫中目前選取之記錄的存取,這個記錄會傳遞至摘要和編輯表單的建構函式,使所有表單都使用相同的繫結來源。除了資料繫結 (Data Binding) 控制項之外,BindingSource 物件可以傳回目前資料列的 DataRowView 物件。您可以基於各種目的,使用 DataRowView 存取資料,例如,判斷資料行目前的值。請注意,基於示範目的,在這個範例中,針對摘要和編輯表單只會用到兩個資料行。

或者,您可以從 DataGrid 控制項上智慧標籤的快速鍵功能表選取 [產生資料表單],以便讓 Visual Studio 自動產生摘要和編輯表單。如需此功能的詳細資訊,請參閱 HOW TO:產生摘要並編輯資料應用程式的檢視 (裝置)

這個應用程式具有下表所述的表單。也列出它們的功能表選項。

表單

功能

功能表選項

主要表單

(Form1)

顯示 DataGrid 控制項。

New

新增一筆記錄至資料庫,並顯示 EditView 表單。

Edit

顯示 EditView 表單。

SummaryView

顯示目前資料錄的資料行值 (已依檢視需求進行最佳化)。

(無)

EditView

顯示目前資料錄的資料行值 (已依編輯需求進行最佳化)。

Done

接受對話方塊、更新資料庫並顯示主要表單。

Cancel

取消對話方塊並顯示主要表單。

若要建立專案並設計主要表單

  1. 在 Visual Studio 中,建立智慧型裝置專案,並將目標平台設定為 Windows Mobile 5.0 Pocket PC SDK 或 Windows Mobile 6 Professional SDK。

  2. 在 [資料] 功能表上,請按 [加入新資料來源]。

  3. 在 [資料來源組態精靈],利用 Microsoft SQL Server Compact 版 (.NET Framework Data Provider for SQL Server CE) 連接至 [Northwind] 資料庫。[Northwind] 資料庫 Northwind.sdf 安裝在 \Program Files\Microsoft SQL Server Compact Edition\v3.5\Samples 資料夾中。

    注意事項:

    在 Windows Vista 上,您必須以系統管理員的身分執行 Visual Studio,才能存取 Northwind 資料庫。如需加入資料庫的詳細資訊,請參閱 HOW TO:將資料庫加入至裝置專案

  4. 在精靈的 [選擇您的資料庫物件] 頁面中,選取 [Products] 資料表及其所有資料行。

  5. 從 [工具箱] 中,將 DataGrid 控制項加入至表單。依需要設定其大小和配置屬性。

  6. DataSource 屬性設定為 [Products] 資料表。Visual Studio 會將 NorthwindDataSet、ProductsBindingSource 和 ProductsTableAdapter 物件加入您的專案中。

  7. DataGridTableStyle 物件加入至 TableStyles 集合,以建立 DataGrid 控制項的樣式,從資料表顯示一或兩個資料行。按一下 [屬性] 窗格中的 [TableStyles] 屬性。這個動作會顯示 [DataGridTableStyle 集合編輯器] 對話方塊。然後執行以下步驟:

    1. 加入 DataGridTableStyle 物件至 TableStyles 集合。

    2. 將 [MappingName] 設定為 "Products"。

    3. 按一下 [GridColumnStyle] 屬性。這個動作會顯示 [DataGridColumnStyle 集合編輯器] 對話方塊。

    4. 加入 DataGridTextBoxColumn 物件至 GridColumnStyles 集合。

    5. 按一下 [MappingName] 屬性,然後選取 [Product Name]。

    6. 設定所需的 [頁首文字] 及 [寬度]。

    7. 在其他資料行中重複這個動作。

    8. 關閉對話方塊。

  8. 將兩個表單加入至專案,一個用於摘要檢視,一個用於編輯檢視。將它們命名為 SummaryView 和 EditView。

  9. 為 SummaryView 和 EditView 資料表的建構函式加入一個參數,以取得 BindingSource 物件。在要設定為傳入建構函式之 BindingSource 物件的這些表單中,宣告一個名為 CurrentBindingSouce 的全域變數。請注意,應在呼叫 InitializeComponent 方法之前設定它。

    Visual Basic 開發人員必須將 [Sub New] 加入至表單,方法是從程式碼窗格右上角的 [方法名稱] 清單加入 [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();
    }
    
  10. 在主要表單中,加入名為 New(MenuItem1) 的 MenuItem 物件,以及另一個名為 Edit (MenuItem2) 的物件。為 New 和 Edit 的 Click 事件加入下列程式碼。

    ' Add new record.
    Private Sub MenuItem1_Click(ByVal sender As System.Object,_
      ByVal e As System.EventArgs) Handles MenuItem1.Click
        ProductsBindingSource.AllowNew = True
        ProductsBindingSource.AddNew()
    
        ' Pass the binding source to the form.
        Dim EditViewDialog As New EditView(ProductsBindingSource)
        If EditViewDialog.ShowDialog() <> DialogResult.OK Then
            ProductsBindingSource.CancelEdit()
        Else
            ProductsBindingSource.EndEdit()
            Me.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 MenuItem2.Click
    
        ' Pass the binding source to the form.
        Dim EditViewDialog As New EditView(ProductsBindingSource)
        If EditViewDialog.ShowDialog() <> DialogResult.OK Then
            ProductsBindingSource.CancelEdit()
        Else
            ProductsBindingSource.EndEdit()
            Me.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);
        }
    }
    
  11. 在主要表單中,為 DataGrid 控制項加入 KeyDown 事件的程式碼,當您在 Pocket PC 上按下動作鍵時,就會發生這個事件。這個動作會顯示 SummaryView 表單。

    ' Action button pressed.
    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 New SummaryView(ProductsBindingSource)
            SummaryViewDialog.ShowDialog()
        End If
    End Sub
    
    // Action button pressed.
    private void dataGrid1_KeyDown(object sender, KeyEventArgs e)
    {
        if (e.KeyCode == Keys.Enter)
        {
            SummaryView SummaryViewDialog = 
              new SummaryView(productsBindingSource);
            SummaryViewDialog.ShowDialog();
         }
    }
    

若要建立摘要檢視

  1. 將下列控制項加入至 SummaryView 表單:

    • 用於 [Product Name] 標題的 Label 控制項,例如 "Product Name:"。

    • 用於 [Product Name] 值的 Label 控制項。

    • 用於 [Discontinued] 值的 Label 控制項,只有在產品資料表的 [Discontinued] 資料行值是 true 時,才會顯示。以紅色字型將這個標籤的標題設為 "DISCONTINUED"。

  2. 將下列程式碼加入至 SummaryView 表單的建構函式,以設定資料繫結。宣告一個名為 CurrentBindingSource 的表單變數,表示表單建構函式中傳入 BindingSource 執行個體的參數。DataRowView 物件可以決定如果 [Discontinued] 資料行為 true,則顯示 [Discontinued] 標籤。

    'Dim CurrentBindingSource As BindingSource
    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.
        ' 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;
        }
    }
    

若要建立編輯檢視

  1. 在您的專案中加入 Microsoft.WindowsCE.Forms 命名空間的參考。

  2. 從 [工具箱] 將 InputPanel 元件拖曳至 EditView 表單。只需要一個執行個體,就能提供使用者螢幕小鍵盤 (SIP),將文字輸入文字方塊中。

  3. 將下列控制項加入至表單:

    • 用於 [Product Name] 文字方塊的 Label 控制項。

    • 用於 [Product Name] 資料行的 TextBox 控制項。

    • 用於 [Discontinued] 資料行的 CheckBox 控制項。將 ThreeState 屬性設定為 true。

  4. 若要設定資料繫結,請在 InitializeComponent 呼叫之後,將下列程式碼加入至表單的建構函式。這個程式碼可讓您加入新的記錄或編輯現有的記錄。如果正在加入新的記錄,DataRowView 物件將判斷 [Discontinued] 資料行是否具有 null 值,並將繫結的 NullValue 屬性設定為 CheckState 屬性的 Indeterminate 值。

    Public Sub New(ByVal bsource As BindingSource)
        CurrentBindingSource = bsource
        InitializeComponent()
        ' Add the bindings.
        ProductNameTextBox.DataBindings.Add("Text",_
      CurrentBindingSource, "Product Name")
        Dim drView As DataRowView
        drView = CurrentBindingSource.Current
        If IsDBNull(drView("Discontinued")) Then
            DiscontinuedCheckBox.DataBindings.Add("CheckState",_
              CurrentBindingSource, "Discontinued", True,_
              DataSourceUpdateMode.OnValidation, _
              CheckState.Indeterminate)
        Else
            DiscontinuedCheckBox.DataBindings.Add("Checked",_
             CurrentBindingSource, "Discontinued")
        End If
    End Sub
    
    public EditView(BindingSource bsource)
    {
        CurrentBindingSource = bsource;
         InitializeComponent();
         CurrentBindingSource = bsource;
         InitializeComponent();
         //  Add the bindings.
         productNameTextBox.DataBindings.Add("Text",
           CurrentBindingSource, "Product Name");
         DataRowView drView;
         drView = (DataRowView) CurrentBindingSource.Current;
         if (drView("Discontinued") == null)
         {
             DiscontinuedCheckBox.DataBindings.Add("CheckState",
               CurrentBindingSource, "Discontinued", true,
               DataSourceUpdateMode.OnValidation,
               CheckState.Indeterminate);
         }
         else
         {
              DiscontinuedCheckBox.DataBindings.Add("Checked",
                CurrentBindingSource, "Discontinued");
         }
    }
    
  5. 加入標題為 Done 的 MenuItem 物件,以利用變更來更新資料庫並回到主要表單。

    ' Done
    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
    // Done
    private void menuItem1_Click(object sender, EventArgs e)
    {
        this.DialogResult = DialogResult.OK;
        this.Close();
    }
    
  6. 在與 [Done] 相同的層級上,加入標題為 Cancel 的 MenuItem 物件,以捨棄變更並回到主表單。

    ' Cancel
    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
    
    // Cancel
    private void menuItem1_Click(object sender, EventArgs e)
    {
        this.DialogResult = DialogResult.Cancel;
        this.Close();
    }
    

編譯程式碼

這個範例需要下列命名空間的參考:

請參閱

工作

HOW TO:在 Smartphone 上使用 DataGrid

概念

產生強型別的 DataSet (ADO.NET)

其他資源

.NET Compact Framework 中的資料存取和 XML 支援