• September 23, 2021

PHSARIT

Bring Technology Ideas with you

 Simple SQL Select from Database using C# and SQL Server

In order to retrieve data from database, you need to go to your Database and Create New Database

    With your new database, please Create New Table

      Go back to your Window Forms Application. If you do not know how to create Window Forms, please visit our previous post by Trick in Create C# Window Form Application

      Within your Form, please design by adding Datagridview

        Go to Properties –> Then Text and name it ( SQL_SELECT)

          Double click on your Form to code ( In your using System, please add (using System.Data.Sql; using System.Data.SqlClient;)

            • Create connection while Form Load as below

            private void Form1_Load(object sender, EventArgs e)
            {
            //declare connection to sql server using Window security
            String StringConnection;
            StringConnection = @”Data Source =HEM_TOLA\SQLEXPRESS; Initial Catalog =SQL_SimpleSelect; Integrated Security = True”;
            cn = new SqlConnection(StringConnection);
            try
            {
            cn.Open();
            MessageBox.Show(“successfully”);
            }
            catch (Exception ex)
            {
            //if there is no connection, it will show
            MessageBox.Show(ex.ToString());
            }

            Create SQL Select Command

            string sqlString;
            sqlString = “select * from Storage”; // select data from table Storage
            SqlDataAdapter dataAdapter = new SqlDataAdapter(sqlString, cn); // Put it into table to store memory using Adapter
            SqlCommandBuilder cmd = new SqlCommandBuilder(dataAdapter);// execute table after storing
            DataTable table = new DataTable(); // create new table to fill table from memory
            dataAdapter.Fill(table); // fill data into Datagridview
            dataGridView1.DataSource = table;// show data on Datagridview to view on form
            //dtShow.DataBindings;

                *** We are using Window Authentications

                Related post