Blue Theme Orange Theme Green Theme Red Theme
 
Mindcracker MVP Summit 2012
Home | Forums | ASP.NET 2.0 Tutorials | Web Services | How Do I...? | Class Browser | WPF Quick Starts | Advertise with Us
 | Consulting  
Submit an Article Submit a Blog 
 Jump to
Skip Navigation Links
TechnologyExpand Technology
WebsiteExpand Website
Mindcracker MVP Summit 2012
Search :       Advanced Search »
Home » ASP.NET 2.0/3.5 » DropDownList in data binding

DropDownList in data binding

This article shows that how we can access data from database in a DropDownList.

Author Rank :
Page Views : 82717
Downloads : 530
Rating :
 Rate it
Level : Beginner
   Print Read/Post comments Post a comment  Similar Articles  
   Email to a friend  Bookmark  Author's other articles  
Download Files:
DropDownListIndataAccess.zip
 
 
Mindcracker MVP Summit 2012
Become a Sponsor
Become a Sponsor
 Tag Cloud
 Latest Jobs
More ... 
 Latest Interview Questions
More ... 

In this article I am going to show that how we can fetch data in a DropDownList from Sql server. Here I used a DropDownList in which on the load of form the Name value will come from a record table.
 

In fetching data from database in a DropDownList we have to set a property of DropDownList like as.

 

DroplistData.DataTextField = "Name";

 

In DropDownList we can fetch only one column value at a time.

 

Firstly I designed a form where I used a DopDownList. In which all value of one selected column will come. I also used a button and a DataGrid here. On clicking of button the complete record will show in DataGrid of that value which user select from DropDownList.

DropDownListIndataAccess.aspx

<%@ Page Language="C#" AutoEventWireup="true"  CodeFile="Default.aspx.cs" Inherits="_Default" Debug="true" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml" >

<head runat="server">

    <title>DropDownListIn Data accessing</title>

</head>

<body>

    <form id="form1" runat="server">

    <div>

        <table cellpadding="0" cellspacing="0" border="4" width="50%" align="center">

          <tr><td>

            <asp:DropDownList ID="DroplistData" runat="server" Width="200px" >

            </asp:DropDownList>

          </td></tr>

         

          <tr><td><table>

          <tr><td>&nbsp;</td></tr>

          <tr><td>  

            <asp:Button ID="ShowDataGrid" runat="server" Text="Click Here To Show The Full record of Selected Name " OnClick="GridShow_Click" />

          </td></tr>

          </table></td></tr>

   

         <tr><td> <asp:DataGrid ID="datagrid" runat="server"></asp:DataGrid></td></tr>

       </table>

     </div>

   </form>

</body>

</html>

DropDownListIndataAccess.aspx.cs
 

using System;

using System.Data;

using System.Configuration;

using System.Web;

using System.Web.Security;

using System.Web.UI;

using System.Web.UI.WebControls;

using System.Web.UI.WebControls.WebParts;

using System.Web.UI.HtmlControls;

using System.Data.SqlClient;

 

public partial class _Default : System.Web.UI.Page

{

    SqlConnection con;

    SqlCommand cmd=new SqlCommand();

    SqlDataAdapter da;

    DataSet ds = new DataSet();

 

    protected void Page_Load(object sender, EventArgs e)

    {

        if (!IsPostBack)

        {

            rebind();

        }

    }

 

    public void rebind()

    {

        try

        {

            con = new SqlConnection("Data Source=MCN0100;Initial Catalog = DropDowndataBase; Uid=sa; Pwd=");

            cmd.CommandText = "select * from Record";

            cmd.Connection = con;

            con.Open();

            DroplistData.DataSource = cmd.ExecuteReader();

            DroplistData.DataTextField = "Name";

            DroplistData.DataBind();

        }

        catch (Exception ex)       

        {

            Response.Write(ex.StackTrace);

        }   

    }

 

    public void datashow()

    {

        con = new SqlConnection("Data Source=MCN0100;Initial Catalog = DropDowndataBase; Uid=sa; Pwd=");

        string nameshow = DroplistData.Text.ToString().Trim();

        cmd.CommandText = "select * from Record where Name='" + nameshow + "' ";

        cmd.Connection = con;

        da = new SqlDataAdapter(cmd);

        da.Fill(ds);

        con.Open();

        cmd.ExecuteNonQuery();

        datagrid.DataSource = ds;

        datagrid.DataBind();

        con.Close();

    }

 

    protected void GridShow_Click(object sender, EventArgs e)

    {

        datashow();

    }  

}

When user will run the application then the window will look like this:



Figure 1: Here all name are coming in DropDownList.



Figure 2: If I select Aaryan and click on button then complete record of Aaryan comes in DataGrid.

Comment Request!
Thank you for reading this post. Please post your feedback, question, or comments about this post Here.
Login to add your contents and source code to this article
 [Top] Rate this article
 
 About the author
 
Rahul Kumar Saxena
Rahul shows great interests in working with Microsoft technologies. He specializes in the implementation of DataBase & Graphics. His area of expertise includes: C#, ASP.NET,ADO.NET,Windows Forms & Web Services. He hails from background , Master's in Computer Application. With programming he loves photography, traveling and reading books.
(Talabpur*)
Looking for C# Consulting?
C# Consulting is founded in 2002 by the founders of C# Corner. Unlike a traditional consulting company, our consultants are well-known experts in .NET and many of them are MVPs, authors, and trainers. We specialize in Microsoft .NET development and utilize Agile Development and Extreme Programming practices to provide fast pace quick turnaround results. Our software development model is a mix of Agile Development, traditional SDLC, and Waterfall models.
Click here to learn more about C# Consulting.
 
Introducing MaxV - one click. infinite control. Hyper-V Hosting from MaximumASP.
Finally – a virtual platform that delivers next-generation Windows Server 2008 Hyper-V virtualization technology from a managed hosting partner you can truly depend on. Visit www.maximumasp.com/max for a FREE 30 day trial. Hurry offer ends soon. Climb aboard the MaxV platform and take advantage of High Availability, Intelligent Monitoring, Recurrent Backups, and Scalability – with no hassle or hidden fees. As a managed hosting partner focused solely on Microsoft technologies since 2000, MaximumASP is uniquely qualified to provide the superior support that our business is built on. Unparalleled expertise with Microsoft technologies lead to working directly with Microsoft as first to offer IIS 7 and SQL 2008 betas in a hosted environment; partnering in the Go Live Program for Hyper-V; and product co-launches built on WS 2008 with Hyper-V technology.
Dynamic PDF
ceTE software specializes in components for dynamic PDF generation and manipulation. The DynamicPDF™ product line allows you to dynamically generate PDF documents, merge PDF documents and new content to existing PDF documents from within your applications.
Discover the top 5 tips for understanding .NET
Ricky Leeks presents the top 5 tips for understanding .NET Interoperability. Learn more.
Nevron Chart for .NET 2010.1 Now Available
The leading .NET charting control now features PDF, Flash and Silverlight export, visualization of large datasets and more. Deliver true charting functionality to your BI, Scorecard, Presentation or Scientific apps. Download evaluation now.
ASP.NET 4 Hosting
Get 2 Months Free of ASP.NET Hosting for Only $4.95/month! Receive FREE MS SQL and MySQL Databases Including ASP.NET 4/3.5, MVC 3.0, Silverlight 4, Windows 2008/IIS 7.0 Plus FREE IIS 7 Modules. Host UNLIMITED ASP.NET Web Sites – Click Here!
 
 Post a Feedback, Comment, or Question about this article
Subject:
Comment:
Discover the top 5 tips for understanding .NET Interop
Become a Sponsor
 Comments
Hi Raahul i need your help by Surya On March 7, 2008
I have not user webservices. Can you tell me the complete procedure how we can create webservices and how we can subscribe them. Please, reply me ASAP.
Reply | Email | Modify 
Re: Hi Raahul i need your help by Rahul Kumar On March 10, 2008

Thanx SURYA TO View Amy Article I will With u With Ur Need Very Soon

Thanx

 

 

Reply | Email | Modify 
I Need your Help by Priyu On July 13, 2011
I saw your Post which is very helpful for me , i want to learn asp.net from you, my mail id is priyaarya5@gmail.com and give me your mail id by which i take your help ................. thanks your Post i waiting for your Response.......
Reply | Email | Modify 
please help me by Ivan On November 17, 2008

hi Raahul, i've tried the code u write to binding data from database to dropdownlist. but it don't show anything at the dropdownlist. it appears to error with the message "'cmbKabupaten' has a SelectedValue which is invalid because it does not exist in the list of items.\r\nParameter name: value" string.

the code i write is shown below :

protected void cmbPropinsi_SelectedIndexChanged(object sender, EventArgs e)

{

  //cmbPropinsi is a dropdownlist which items has been listed manual (not from database)  

fillCmbKabupaten();

}

private void fillCmbKabupaten()

{

//cmbKabupaten is a dropdownlist which items i tried to bind from database according to the selected item on cmbPropinsi

cmbKabupaten.Text = String.Empty;

try {

DataSet ds1 = pendaftaranM.getKabupatenByPropName(cmbPropinsi.SelectedValue.ToString());

cmbKabupaten.DataSource = ds1;

cmbKabupaten.DataTextField = "nama_kabupaten";

cmbKabupaten.DataBind();

}

catch (System.Data.SqlClient.SqlException e1)

{ cmbKabupaten.Text = String.Empty + e1.Message; }

catch (Exception e2)

{ cmbKabupaten.Text = String.Empty + e2.Message; }

 }

the method getKabupatenByPropName is shown below :

public DataSet getKabupatenByPropName(string nama_prop)

{

try {

DataSet ds = new DataSet();

con.Open();

SqlCommand cmd = new SqlCommand("GetKabupatenByPropName", con);

cmd.CommandType = CommandType.StoredProcedure;

cmd.Parameters.Add(new SqlParameter("@nama_prop", SqlDbType.VarChar, 50));

cmd.Parameters["@nama_prop"].Value = nama_prop;

SqlDataAdapter da = new SqlDataAdapter(cmd);

da.Fill(ds, "REF_KABUPATEN");

return ds;

}

catch (SqlException ex)

{ throw new ApplicationException(ex.Message); }

catch (Exception ex) { throw new ApplicationException(ex.Message); } finally { con.Close(); }

}

i used stored procedure here

CREATE PROCEDURE GetKabupatenByPropName

@nama_prop varchar(50)

AS

select kab.nama_kabupaten

from ref_kabupaten kab, ref_propinsi prop

where kab.kd_prop = prop.kd_prop and prop.nama_prop = @nama_prop  please help me, i'm really stressout with this... please reply me ASAP thank u very much...

Reply | Email | Modify 
Re: please help me by Lawrence On September 18, 2009
Thanks for ur kindly information. It's good to us....
Reply | Email | Modify 
How to add sub-menus to main menu by Avi On July 14, 2010
How to add or store Sub-menus to main menus in sql database and retrive from sql database ?

let me explain, in above exmple, in dropdown box there is one main menu "Rahul". if want to add sub-menus to " Rahu " menu like 1)home 2)book 3)college. then what i need to do. how i add these submenus in sql database and retrive form database.



please help me... my carrer depends on this project...


please send me code as soon as posible
Reply | Email | Modify 
tankxx by tari On November 9, 2010
very usefull post
tanksssssxxxx
Reply | Email | Modify 
send sms using asp.net application by ashish On September 24, 2011
hiiiiii rahul kumar thnks to help me i have one quetion that tell me about some code or some sites link they can help me to send the mobile sms using the asp.net application or send me mail my id ashish_ashish_20072007@yahoo.com plssss help me i have try that but i cant sucess to send sms
Reply | Email | Modify 
Nevron Chart
 © 2012  contents copyright of their authors. Rest everything copyright Mindcracker. All rights reserved.