C# form applies DataGridView, and uses database (Sql and MySQl) to bind data source to DataGridView to obtain data

Posted by arjan.top on Thu, 21 Oct 2021 16:52:26 +0200

preface

Previously, we used class library objects for data binding. If you don't understand children's shoes, you can go to the previous article of the blogger. Today, I'll show you how to use the database to bind data to the datadriveview. In fact, it's also very simple. Let's roll it up.

Once a day to prevent decadence

1.1 let's get to the point

1.1.2 (method 1) use the codeless method to use database binding

1.1.3 create a new connection and establish your own database link

1.1.4 select the link you just established. If you use a password, select Yes, otherwise the link will fail and the login will not succeed

1.1.5 select the table and Id you need. If you need the whole database, select all.

1.1.6 effect display. If you need to add a new query, click the data source below to add it.

2.1 use code to bind DataGridView (including MySQL)

2.1.1 there are many ways to use code. Xiaobian tries to write out the methods Xiaobian knows. Double click button1 to generate the methods

2.1.2 connect to the database, obtain data, and bind the data grid view

 private void button1_Click(object sender, EventArgs e)
        {
            string connString = "server=.;database= StudentDB; User ID = sa; Pwd=123456";
            SqlConnection conn = new SqlConnection(connString);
            SqlCommand comm = new SqlCommand();
            comm.Connection = conn;
            string sql = String.Format("select course_id 'number',course_name 'Course name',teacher_name 'Teacher name' from T_course");
            try
             {
               
                conn.Open();
                SqlDataAdapter da = new SqlDataAdapter(sql, connString);
                DataSet ds = new DataSet();
                da.Fill(ds);
                dataGridView1.DataSource = ds.Tables[0];
                conn.Close();
              }
            catch (Exception ex)
                {
                       MessageBox.Show(ex.Message, "Error operating database!", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);

                }            
            }

2.1.3 effect display: the blogger uses the SqL Server database.

2.1.4 in fact, there are other methods for the code. Bloggers will show them

  string connString = "server=.;database= StudentDB; User ID = sa; Pwd=123456";
            SqlConnection conn = new SqlConnection(connString);
            SqlCommand comm = new SqlCommand();
            comm.Connection = conn;
           // string sql = String.Format("select course_id 'number', course_name 'course name', teacher_name 'teacher name' from T_course");
            try
             {
               
                conn.Open();
                string sql = "select course_id ,course_name,teacher_name from T_course";
                SqlDataAdapter da = new SqlDataAdapter(sql, connString);
                DataSet ds = new DataSet();
                da.Fill(ds,"studens");da. Fill (ds, "students");//Parameter 1: dataset object; Parameter 2: name, user-defined name, unnecessary and query table name must be - to
                //When method 1 is used, other methods are annotated
                dataGridView1.DataSource = ds;
                dataGridView1.DataMember ="studens";
                //Method 2
                dataGridView1.DataSource = ds.Tables["studens"];
                //Method 3
                DataTable dt = ds.Tables["studens"];
                dataGridView1.DataSource = dt.DefaultView;
                conn.Close();
              }
            catch (Exception ex)
                {
                       MessageBox.Show(ex.Message, "Error operating database!", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);

                }            

2.1.5 using MySQL, you can also perform data binding on datagridview, change the database connection mode, and front those types as My, and the others are the same. You are prompted to import the namespace. Alt + end can be imported quickly. If not, you will be asked to download it.

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Data.SqlClient;
using MySql.Data.MySqlClient;

namespace student
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e)
        {
          

        }

        private void button1_Click(object sender, EventArgs e)
        {
            string connString = "server=localhost; database=student; uid=root; pwd=88888888;Character Set=utf8;";
            MySqlConnection conn = new MySqlConnection(connString);
            MySqlCommand comm = new MySqlCommand();
            comm.Connection = conn;
           // string sql = String.Format("select course_id 'number', course_name 'course name', teacher_name 'teacher name' from T_course");
            try
             {
               
                conn.Open();
                string sql = "select course_id ,course_name,teacher_naem from T_course";
                MySqlDataAdapter da = new MySqlDataAdapter(sql, connString);
                DataSet ds = new DataSet();
                da.Fill(ds,"studens");
                //Method 1
                dataGridView1.DataSource = ds;
                dataGridView1.DataMember ="studens";
                //Method 2
               /* dataGridView1.DataSource = ds.Tables["studens"];
                //Method 3
                DataTable dt = ds.Tables["studens"];
                dataGridView1.DataSource = dt.DefaultView;*/
                conn.Close();
              }
            catch (Exception ex)
                {
                       MessageBox.Show(ex.Message, "Error operating database!", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);

                }            
            }
    }
}

summary

The blogger has basically finished writing the DataGridView control. In writing the article, he has learned a lot, consolidated his knowledge, and learned new things. datagirdview also has a data source called "service". The blogger has not learned this knowledge, but only knows that if you want to use a database similar to Alibaba cloud, You can use third-party database software to connect and then embed. Hahaha, of course, this method may be a little silly, but bloggers only know this, or you can learn WEf services. It's not easy to create. I hope you can praise, comment and pay attention. Thank you!!!

Topics: C# Database SQL