• Добро пожаловать на сайт - Forumteam.wiki !

    Что бы просматривать темы форума необходимо зарегестрироваться или войти в свой аккаунт.

    Группа в телеграме (подпишитесь, что бы не потерять нас) - ForumTeam Chat [Подписатся]
    Связь с администратором - @ftmadmin

61. Читаем базу данных опять.

Redman

<FORUMTEAM>
Команда форума
Регистрация
13.11.17
Сообщения
13.343
Реакции
8.371
Баллы
1.200
FTC
203¢
Практический пример на чтение данных из базы данных.
Данный пример показывает принцип чтения данных из базы данных. Программа отображает в сетку содержимое таблицы. В примере используется параметр для фильтрования полученных данных. Код примера:
Код:
using System;
using System.Drawing;
using System.Collections;
using System.ComponentModel;
using System.Windows.Forms;
using System.Data;
// Пространство для классов Ole
using System.Data.OleDb;
namespace Params
{
    ///

    /// Summary description for Form1.
    ///

    public class Form1 : System.Windows.Forms.Form
    {
        // Переменная для сетки
        private System.Windows.Forms.DataGrid dataGrid1;
        private System.Windows.Forms.Button button2;
        private System.Windows.Forms.Label label1;
        private System.Windows.Forms.Button button1;
        ///

        /// Required designer variable.
        ///

        private System.ComponentModel.Container components = null;

        public Form1()
        {
            //
            // Required for Windows Form Designer support
            //
            InitializeComponent();

            //
            // TODO: Add any constructor code after InitializeComponent call
            //
        }

        ///

        /// Clean up any resources being used.
        ///

        protected override void Dispose( bool disposing )
        {
            if( disposing )
            {
                if (components != null)
                {
                    components.Dispose();
                }
            }
            base.Dispose( disposing );
        }

        #region Windows Form Designer generated code
        ///

        /// Required method for Designer support - do not modify
        /// the contents of this method with the code editor.
        ///

        private void InitializeComponent()
        {
            this.dataGrid1 = new System.Windows.Forms.DataGrid();
            this.button2 = new System.Windows.Forms.Button();
            this.label1 = new System.Windows.Forms.Label();
            this.button1 = new System.Windows.Forms.Button();
            ((System.ComponentModel.ISupportInitialize)(this.dataGrid1)).BeginInit();
            this.SuspendLayout();
            //
            // dataGrid1
            //
            this.dataGrid1.DataMember = "";
            this.dataGrid1.HeaderForeColor = System.Drawing.SystemColors.ControlText;
            this.dataGrid1.Location = new System.Drawing.Point(16, 64);
            this.dataGrid1.Name = "dataGrid1";
            this.dataGrid1.Size = new System.Drawing.Size(576, 384);
            this.dataGrid1.TabIndex = 0;
            //
            // button2
            //
            this.button2.Location = new System.Drawing.Point(632, 64);
            this.button2.Name = "button2";
            this.button2.TabIndex = 1;
            this.button2.Text = "Заполнить";
            this.button2.Click += new System.EventHandler(this.button2_Click);
            //
            // label1
            //
            this.label1.Location = new System.Drawing.Point(16, 8);
            this.label1.Name = "label1";
            this.label1.TabIndex = 2;
            this.label1.Text = "Данные";
            //
            // button1
            //
            this.button1.Location = new System.Drawing.Point(632, 120);
            this.button1.Name = "button1";
            this.button1.TabIndex = 3;
            this.button1.Text = "Параметры";
            this.button1.Click += new System.EventHandler(this.button1_Click);
            //
            // Form1
            //
            this.AutoScaleBaseSize = new System.Drawing.Size(5, 13);
            this.ClientSize = new System.Drawing.Size(712, 462);
            this.Controls.Add(this.button1);
            this.Controls.Add(this.label1);
            this.Controls.Add(this.dataGrid1);
            this.Controls.Add(this.button2);
            this.Name = "Form1";
            this.Text = "ADO.NET";
            ((System.ComponentModel.ISupportInitialize)(this.dataGrid1)).EndInit();
            this.ResumeLayout(false);

        }
        #endregion

        ///

        /// The main entry point for the application.
        ///

       
        static void Main()
        {
            Application.Run(new Form1());
        }

        private void button2_Click(object sender, System.EventArgs e)
        {
            try
            {           
                // Присоединение к базе данных
                OleDbConnection connect = new  OleDbConnection();       
                // Строка соединения с Ole -  провайдером
                connect.ConnectionString = @"Provider=Microsoft.Jet.OLEDB.4.0;data 
source=c:\sample.mdb";
                connect.Open();
                OleDbCommand command = new OleDbCommand();
                // Запрос
                command.CommandText = "select * from people";
                command.Connection = connect;
                OleDbDataAdapter adapter = new OleDbDataAdapter(command);
                DataSet dataset = new DataSet();
                // Заполнение сетки
                adapter.Fill(dataset,"People");
                dataGrid1.DataSource = dataset.Tables["People"];

            }
            catch(Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

        private void button1_Click(object sender, System.EventArgs e)
        {
            try
            {
                OleDbConnection connect = new  OleDbConnection();       
                connect.ConnectionString = @"Provider=Microsoft.Jet.OLEDB.4.0;data 
source=c:\sample.mdb";
                connect.Open();

                OleDbCommand command = new OleDbCommand();
                // Запрос с параметром   
                command.CommandText = "select * from people where name = ?";
                command.Connection = connect;
               
                OleDbDataAdapter adapter = new OleDbDataAdapter(command);
                // Добавление значения для параметра
                adapter.SelectCommand.Parameters.Add("@name", OleDbType.VarChar, 80).Value = "Oleg";
               

                DataSet dataset = new DataSet();
                adapter.Fill(dataset,"People");
                dataGrid1.DataSource = dataset.Tables["People"];

            }
            catch(Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }
    }
}
 
Сверху Снизу