Site icon SmartTutorials.net

Simple Dot net Application with Database Connection

Following code loads data form database into dropdown box during pageload event and when you select data from dropdown box page is postbacked and data in the database populated in the Grid view control..

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data.SqlClient;

namespace journelapp
{
    public partial class _out : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            SqlConnection conn = new SqlConnection("Integrated Security=true; Server= user-pc\\SQLEXPRESS;Database=journel");
            SqlCommand comd = new SqlCommand();
            SqlDataReader rdr;
            if (!Page.IsPostBack)
            {
                string str;
                conn.Open();
                str = "select login.username from login";
                comd = new SqlCommand(str, conn);
                rdr = comd.ExecuteReader();
                DropDownList1.DataSource = rdr;
                DropDownList1.DataTextField = "username";
                DropDownList1.DataBind();
                rdr.Close();
            }
            else {
                string str;
                GridView1.Visible = true;
                str = "select login.username[User Name],login.password[Password],login.emailid[Email Id] from login";
                conn.Open();
                comd = new SqlCommand(str, conn);
                rdr = comd.ExecuteReader();
                GridView1.DataSource = rdr;
                GridView1.DataBind();
                rdr.Close();  

            }

        }

    }
}

Following data table in the database

Output of the above program during pageload event

Output of the above program after postbacked event

.

Exit mobile version