使用兩個 Windows 表單 DataGridView 控制項建立一個主/從表單

來源:互聯網
上載者:User

標籤:連接字串   密碼   filter   initial   ext   for   tom   lex   hang   

使用 DataGridView 控制項的一種最常見方案是“主/詳細資料”表單,這樣的表單可顯示兩個資料庫表之間的父/子關係。如果選擇主表中的行,將導致以相應的子資料來更新詳細資料表。

主/詳細資料表單很容易實現,這需要使用 DataGridView 控制項和 BindingSource 組件之間的互動。在本演練中,將使用兩個 DataGridView 控制項和兩個 BindingSource 組件來產生表單。表單將顯示 Northwind SQL Server 樣本資料庫中的兩個相關表:Customers 和 Orders。完成後,將得到一個表單,它可以在主 DataGridView 中顯示資料庫中的所有客戶,並在詳細資料 DataGridView 中顯示所選客戶的所有訂單。

建立表單

 建立主/詳細資料表單
  1. 建立一個從 Form 派生的類,該類包含兩個 DataGridView 控制項和兩個 BindingSource 組件。下面的代碼提供了基本的表單初始化,並包含一個 Main 方法。如果使用 Visual Studio 設計器來建立表單,則可以使用設計器產生的程式碼而不是這裡的代碼,但一定要使用這裡的變數聲明中顯示的名稱。

  2. using System; using System.Data; using System.Data.SqlClient; using System.Windows.Forms;
    public class Form1 : System.Windows.Forms.Form {     private DataGridView masterDataGridView = new DataGridView();     private BindingSource masterBindingSource = new BindingSource();     private DataGridView detailsDataGridView = new DataGridView();     private BindingSource detailsBindingSource = new BindingSource();
        [STAThreadAttribute()]     public static void Main()     {         Application.Run(new Form1());     }
        // Initializes the form.     public Form1()     {         masterDataGridView.Dock = DockStyle.Fill;         detailsDataGridView.Dock = DockStyle.Fill;
            SplitContainer splitContainer1 = new SplitContainer();         splitContainer1.Dock = DockStyle.Fill;         splitContainer1.Orientation = Orientation.Horizontal;         splitContainer1.Panel1.Controls.Add(masterDataGridView);         splitContainer1.Panel2.Controls.Add(detailsDataGridView);
            this.Controls.Add(splitContainer1);         this.Load += new System.EventHandler(Form1_Load);         this.Text = "DataGridView master/detail demo";     } }

  3. 在表單的類定義中實現一個方法,用於處理有關與資料庫的串連的詳細資料。此樣本使用 GetData 方法來填充 DataSet 對象,並向資料集添加 DataRelation 對象,還要綁定 BindingSource 組件。務必將 connectionString 變數設定為適用於您的資料庫的值,將敏感資訊(如密碼)儲存在連接字串中可能會影響應用程式的安全性。若要控制對資料庫的訪問,一種較為安全的方法是使用 Windows 身分識別驗證(也稱為整合式安全性)。有關更多資訊,請參見保護連接字串。

  4. private void GetData() {     try     {         // Specify a connection string. Replace the given value with a         // valid connection string for a Northwind SQL Server sample         // database accessible to your system.         String connectionString =             "Integrated Security=SSPI;Persist Security Info=False;" +             "Initial Catalog=Northwind;Data Source=localhost";         SqlConnection connection = new SqlConnection(connectionString);
            // Create a DataSet.         DataSet data = new DataSet();         data.Locale = System.Globalization.CultureInfo.InvariantCulture;
            // Add data from the Customers table to the DataSet.         SqlDataAdapter masterDataAdapter = new             SqlDataAdapter("select * from Customers", connection);         masterDataAdapter.Fill(data, "Customers");
            // Add data from the Orders table to the DataSet.         SqlDataAdapter detailsDataAdapter = new             SqlDataAdapter("select * from Orders", connection);         detailsDataAdapter.Fill(data, "Orders");
            // Establish a relationship between the two tables.         DataRelation relation = new DataRelation("CustomersOrders",             data.Tables["Customers"].Columns["CustomerID"],             data.Tables["Orders"].Columns["CustomerID"]);         data.Relations.Add(relation);
            // Bind the master data connector to the Customers table.         masterBindingSource.DataSource = data;         masterBindingSource.DataMember = "Customers";
            // Bind the details data connector to the master data connector,         // using the DataRelation name to filter the information in the         // details table based on the current row in the master table.         detailsBindingSource.DataSource = masterBindingSource;         detailsBindingSource.DataMember = "CustomersOrders";     }     catch (SqlException)     {         MessageBox.Show("To run this example, replace the value of the " +             "connectionString variable with a connection string that is " +             "valid for your system.");     } }

  5. 為表單的 Load 事件實現一個處理常式,該事件將 DataGridView 控制項綁定到 BindingSource 組件,並調用 GetData 方法。下面的樣本所包括的代碼可以調整 DataGridView 列的大小,以容納所顯示的資料。

  6. private void Form1_Load(object sender, System.EventArgs e) {     // Bind the DataGridView controls to the BindingSource     // components and load the data from the database.     masterDataGridView.DataSource = masterBindingSource;     detailsDataGridView.DataSource = detailsBindingSource;     GetData();
        // Resize the master DataGridView columns to fit the newly loaded data.     masterDataGridView.AutoResizeColumns();
        // Configure the details DataGridView so that its columns automatically     // adjust their widths when the data changes.     detailsDataGridView.AutoSizeColumnsMode =         DataGridViewAutoSizeColumnsMode.AllCells; }

使用兩個 Windows 表單 DataGridView 控制項建立一個主/從表單

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.