How to bind Sql server database using DropDownList

How to bind database with dropdownlist? First we need to understand some properties of dropdownlist.

DataSource: is the data source

DataBind: data source binding

DataTextField: The text value to display

DataValueField: Displays the number of the text value

Among them, DataTextField is mainly for users to see, and what our programmers use is DataValueField.

Here is the code display:

Here I have created a department table and inserted three pieces of data:

 go
 create table Department
 (
DepId    int primary key identity(1,1),
DepName    nvarchar(50)
 )
 insert into Department values('人事部')
 insert into Department values('开发部')

 insert into Department values('Administration Department')

Here is the personal DBHelper class: (to reference two namespaces: using System.Data;
using System.Data.SqlClient;)

public class DBHelper
    {
        static string Conns = "database=EmployeeSys;uid=sa;pwd=123456;server=.";
        /// <summary>
        /// 执行查询
        /// </summary>
        /// <param name="sql"></param>
        /// <returns></returns>
        public static DataTable Table(string sql)
        {
            using (SqlConnection conn = new SqlConnection(Conns))
            {
                SqlDataAdapter sda = new SqlDataAdapter(sql, conn);
                DataTable dt = new DataTable();
                sda.Fill(dt);
                return dt;
            }
        }
        /// <summary>
        /// Execute additions, deletions and changes
        /// </summary>
        /// <param name="sql"></param>
        /// <returns></returns>
        public static bool InsertOrDelete(string sql)
        {
            using (SqlConnection conn = new SqlConnection(Conns))
            {
                conn.Open();
                SqlCommand cmd = new SqlCommand(sql, conn);
                return cmd.ExecuteNonQuery() > 0;
            }
        }
    }

Here is the data binding for dropdownlist:

 

 string sql = string.Format(" select * from Department");
                DropDownList1.DataSource = DBHelper.Table(sql);
                DropDownList1.DataTextField = "DepName";
                DropDownList1.DataValueField = "DepId";
                DropDownList1.DataBind();



operation result

How can I get the ID value of the item I selected?

  int id=int.Parse(this.DropDownList1.SelectedItem.Value);

Well, this is my little opinion on dropdownlist. If you don't like it, just take a look. Thank you again. I hope it can bring you some help.




Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325735150&siteId=291194637