There are many Options, First you can bind the Dropdown with a Datatable or dataset or a Reader like this
I create a Small Project for you that i have attached. Let me explain the code, Create a Function that will Connect to the DB and Bind the dropdownlist like this
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Data.SqlClient;
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
BindDropdown();
}
}
private void BindDropdown()
{
String COnstring = @"user id=sa;Password=oops;Server=VUYISWA\SSIS_Server;Database=VUYISWA";
SqlConnection Con = new SqlConnection(COnstring);
SqlCommand cmdselect = new SqlCommand();
cmdselect.CommandText = "select ID from dbo.TestTable";
cmdselect.CommandType = CommandType.Text;
cmdselect.Connection = Con;
SqlDataAdapter da = new SqlDataAdapter();
da.SelectCommand = cmdselect;
DataSet ds = new DataSet();
try
{
Con.Open();
da.Fill(ds);
if(ds.Tables[0].Rows.Count > 0)
{
DropDownList1.DataSource = ds;
DropDownList1.DataTextField = ds.Tables[0].Columns[0].ToString();
DropDownList1.DataValueField = ds.Tables[0].Columns[0].ToString();
DropDownList1.DataBind();
}
}
catch(SqlException ex)
{
lblselected.Text = ex.Message;
}
finally
{
Con.Close();
}
}
and when the user selected the dropdownlist the selectedindexchanged event will be fired and the following code will assign a label to the selected item like this
protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)
{
String test = DropDownList1.SelectedItem.Text;
lblselected.Text = test;
}
Thank you for posting at Dotnetfunda
Vuyiswa Maseko
Download source fileThank you for posting at Dotnetfunda
[Administrator]
Shwetabansal888, if this helps please login to Mark As Answer. | Alert Moderator