Hello,
As you have tagged your question with ASP.Net, I am assuming that you are using ASP.Net and C# as your code behind and according I am writing the code below. See if it helps you.
Lets consider that ddlData is the
DropDownList
defined in
aspx
page,
tblCompanies
is the table from which you want to fetch data.
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
loadDropDown();
}
}
public void loadDropDown()
{
string strSelectString = @"select * from tblCompanies";
SqlConnection conn = new SqlConnection("Server=SSK- PC\\MSSQL2008;database=*******;User ID=******;Password=*********;");
conn.Open();
SqlCommand cmd = new SqlCommand(strSelectString, conn);
SqlDataAdapter adapter = new SqlDataAdapter(cmd);
DataSet data = new DataSet();
adapter.Fill(data);
conn.Close();
if(data.Tables[0]!= null && data.Tables[0].Rows.Count > 0)
{
ddlData.DataSource=data.Tables[0];
ddlData.DataValueField = "CompanyId";
ddlData.DataTextField = "CompanyName";
ddlData.DataBind();
}
}