.NET Tutorials, Forums, Interview Questions And Answers
Welcome :Guest
 
Sign In
Register
 
Win Surprise Gifts!!!
Congratulations!!!


Top 5 Contributors of the Month
david stephan

Home >> Code Snippets >> ASP.NET Controls >> Post New Resource Bookmark and Share   

 Subscribe to Code Snippets

Retriving data from database and Add Items to DropDownList uisng C#

Posted By:Syed Shakeer Hussain       Posted Date: March 15, 2009    Points: 10    Category: ASP.NET Controls    URL: http://www.dotnetspark.com  
 

Retriving data from database and Add Items to DropDownList uisng C#

Suppose I created a table name as ddltable,and I have two columns in that table.column names are id and name.I inserted some values in a ddltable.Now I want to retrive a id column values and display in dropdownlist.

We can do this one in two ways.
1)by using DataReader
2)by using DataSet;

Method I :
----------

SqlConnection conn = new SqlConnection(" your connection string ");
conn.Open();
SqlCommand cmd = new SqlCommand("select id from ddltable ", conn);
SqlDataReader dr = cmd.ExecuteReader();
while (dr.Read())
{
DropDownList2.Items.Add(dr["id"].ToString ());

}



Method II:
-----------
SqlConnection conn = new SqlConnection(" your connection string ");
conn.Open();
SqlDataAdapter da = new SqlDataAdapter("select * from ddltable ", conn);
DataSet ds = new DataSet();
da.Fill(ds, " ddltable ");
DropDownList1.DataSource = ds.Tables["ddltable "].DefaultView ;
DropDownList1.DataTextField = "id";
DropDownList1.DataBind();





     

Further Readings:

Responses

No response found. Be the first to respond this post

Post Comment

You must Sign In To post reply
Find More code samples in C#, ASP.Net, Vb.Net and more Here

Hall of Fame    Twitter   Terms of Service    Privacy Policy    Contact Us    Archives   Tell A Friend