DropDownList 資料繫結

來源:互聯網
上載者:User
綁定DataTable//建立一個SqlConnection
        SqlConnection conn = new SqlConnection("Data Source=.;Initial Catalog=pubs;Integrated Security=True");
        
        string SQL_Select = "select job_id,job_desc from dbo.jobs order by job_id desc";

        //構造一個SqlDataAdapter
        SqlDataAdapter myAdapter = new SqlDataAdapter(SQL_Select, conn);

        try
        {
            //開始讀取資料
            conn.Open();
            try
            {
                DataSet dataSet = new DataSet();
                myAdapter.Fill(dataSet, "jobs");

                //指定DropDownList使用的資料來源
                DropDownList1.DataSource = dataSet.Tables["jobs"].DefaultView;

                //指定DropDownList使用的表裡的那些欄位
                DropDownList1.DataTextField = "job_desc"; //dropdownlist的Text的欄位
                DropDownList1.DataValueField = "job_id";//dropdownlist的Value的欄位

                DropDownList1.DataBind();
            }
            catch (Exception ex)
            {
                throw ex;
            }
            finally
            {
                conn.Close();
                conn.Dispose();
            }
        }
        catch (Exception ex)
        {
            throw ex;
        }

綁定枚舉
方法一:可綁定Text和Value.foreach (int i in Enum.GetValues(typeof(EnumArea)))
        {
            ListItem item = new ListItem(Enum.GetName(typeof(EnumArea), i), i.ToString());
            DropDownList1.Items.Add(item);
        }

方法二:只綁定Text.DropDownList1.DataSource = Enum.GetValues(typeof(EnumArea));
DropDownList1.DataBind();

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.