6 Feb 2012

How to Connect Data Source and Display data in Windows form by using C#.NET

The main objective of Windows-based programming is to create applications that are linked to databases, have user-friendly interfaces (Windows forms), and are capable of running on most platforms.The C# language having this capability by creating winforms to connecting data sources using ADO.NET technology.

ADO.NET is the .NET technology for interacting with data sources.By using System.Data.SqlClient Namespace the .NET framework connect to database and perform queries on that and get the data from data source.

The below sample C# windows form application is explains how the application is connecting to SQL server data source and display table data in grid of application.

Execution Process:
First enter Credentials in those required text boxes for Connect to the SQL Server, then click on Connect button. If the credentials are valid the application is connect to SQL server and bind all table list to combo box, after selecting table as item in that combo box the data will display in grid control as a table.
Source Code:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Data.SqlClient;

namespace ConnectToSQLusingCsharpApp
{
    public partial class Form1 : Form
    {
        string server = "";
        string dbName = "";
        string uName = "";
        string psw = "";
        string strConAddr = "";

        SqlConnection sqlCon; //For Connecting to sql
        SqlCommand sqlCmd;// For passing Command to sql
        SqlDataReader sqlDrd;// For storing Output Data from sql command
        DataTable dt;

        public Form1()
        {
            InitializeComponent();
        }

        private void btnConnect_Click(object sender, EventArgs e)
        {
            btnConnect.Enabled = false;
            cmbTable.Items.Clear();
            server = txtServer.Text;
            dbName = txtDb.Text;
            uName = txtUname.Text;
            psw = txtPsw.Text;
            try
            {
                
                strConAddr = "SERVER = " + server + "; Initial Catalog = " + dbName + "; UID = " + uName + "; PWD = " + psw + "";
                sqlCon = new SqlConnection(strConAddr);
                sqlCon.Open();
                sqlCmd = new SqlCommand("SELECT name FROM sys.Tables", sqlCon);
                sqlDrd = sqlCmd.ExecuteReader();
                while (sqlDrd.Read())
                {
                    cmbTable.Items.Add(sqlDrd["name"].ToString());
                }
                if (sqlCon.State == ConnectionState.Open)
                    sqlCon.Close();
                sqlDrd.Dispose();
                btnConnect.Text = "Connected";
            }
            catch (Exception ea)
            {
                MessageBox.Show("Error: "+ea.Message.ToString());
                server = "";
                dbName = "";
                uName = "";
                psw = "";
            }
            btnConnect.Enabled = true;
            cmbTable.Focus();
         }
         
        private void cmbTable_SelectedIndexChanged(object sender, EventArgs e)
        {
            try
            {
                sqlCon = new SqlConnection(strConAddr);
                if (sqlCon.State == ConnectionState.Closed)
                    sqlCon.Open();

                sqlCmd = new SqlCommand("SELECT * FROM [" + cmbTable.SelectedItem.ToString() + "]", sqlCon);
                sqlDrd = sqlCmd.ExecuteReader();
                dt = new DataTable();
                dt.Load(sqlDrd);
                dGrdTbl.DataSource = dt;
                          
                if (sqlCon.State == ConnectionState.Open)
                    sqlCon.Close();
                sqlDrd.Dispose();
                dt.Dispose();
            }
            catch (Exception etbl)
            {
                MessageBox.Show("Error: " + etbl.Message.ToString());
            }
        }
         private void Form1_Load(object sender, EventArgs e)
        {
            btnConnect.Text = "Connect";
        }
       
    }
}


For downloading entire visual studio solution file for this Application CLICK HERE