ASP.NET C# Bind DropDownList Control from SQL Datasource

by Evgelen 4. December 2009 20:03

ASP.NET C# Bind DropDownList Control from SQL Datasource

using System;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;

private void Page_Load(object sender, EventArgs e)
        {
            DropDownListBind();
        }

        public void DropDownListBind()
        {
            var conn = new SqlConnection
              {
                 ConnectionString =
                                   ConfigurationManager.ConnectionStrings["ConnectionString"].ToString()
              };

            var cmd = new SqlCommand("SELECT * FROM TableName", conn);
            cmd.Connection.Open();

            var dropDownListsValues = cmd.ExecuteReader(CommandBehavior.CloseConnection);

            DropDownListControl.DataSource = dropDownListsValues;
            DropDownListControl.DataValueField = "ControlId";
            DropDownListControl.DataTextField = "ControlData";
            DropDownListControl.DataBind();

            cmd.Connection.Close();
            cmd.Connection.Dispose();
        }


private void Page_Load(object sender, EventArgs e)
        {
            DropDownListBind();
        }

        public void DropDownListBind()
        {
            var connectionString = ConfigurationManager.ConnectionStrings["ConnectionString"].ToString();
            using (var conn = new SqlConnection(connectionString))
            {
                var cmd = new SqlCommand("SELECT * FROM TableName", conn);
                cmd.Connection.Open();
                var dropDownListsValues = cmd.ExecuteReader(CommandBehavior.CloseConnection);
                DropDownListControl.DataSource = dropDownListsValues;
                DropDownListControl.DataValueField = "ControlId";
                DropDownListControl.DataTextField = "ControlData";
                DropDownListControl.DataBind();
            }
        }

Tags: , , ,

ASP.NET | C# | SQL

Tag cloud