Drop Down List Binding Data From MSSQL Database Asp.net,C#

Bangalore:Hi Friends today we are going to discuss about Dropdown Lists in Asp.Net web forms, This article for beginners those who just start coding in C#.
Requirements:
Development Tools: Visual Studio,Sql Server Management Studio
Create an Empty web application in Visual Studio and add a Web form to your project.
Add a Drop down box and Button inside your aspx form like this.

<form id="form1" runat="server">
    <div>
    <asp:DropDownList ID="drpData" runat="server" Width="100px"></asp:DropDownList>
    <asp:Button id="btnShow" Text="Show" runat="server" onclick="btnShow_Click" />
    </div>
    </form>

Here In our Application on Page Load Itself Dropdown get filled and on show button click you can see which item you have selected as alert.
On Pageload itself we have called FilledDropDown Function so it will fill our dropdown box, we have called it inside (!Isostback) so the options which you have selected wont change on next page load. Here we have selected the id and firstname from the database and bind that data into our dropdown box. Id we are assigning into valuefield and Text we are assigning  to TextField
please go through the code behind c# code

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.IO;
using System.Data;
using System.Data.Sql;
using System.Data.SqlClient;
namespace Drop
{
    public partial class Default : System.Web.UI.Page
    {
        SqlConnection con = new SqlConnection("Data Source=Tonz-PC; Integrated Security=true;  Initial Catalog=Search");
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                FillDropDown();
            }
        }
        public void FillDropDown()
        {
            con.Open();
            DataTable dt = new DataTable();
            SqlCommand cmd = new SqlCommand("Select id,firstname from users",con);
            SqlDataAdapter sda = new SqlDataAdapter(cmd);
            sda.Fill(dt);
            if (dt.Rows.Count > 0)
            {
                drpData.DataSource = dt;
                drpData.DataValueField=dt.Columns["id"].ToString();
                drpData.DataTextField = dt.Columns["firstname"].ToString();
                drpData.DataBind();
                drpData.Items.Insert(0, " ");
            }
            con.Close();
        }
        protected void btnShow_Click(object sender, EventArgs e)
        {
            ScriptManager.RegisterStartupScript(this,GetType(),"showalert","alert('" + drpData.SelectedItem.Text +"');", true);
         
        }
    }
}

Hope that you got everything,write to us if you have any doubts.

0 comments: