---
# System prepended metadata

title: WebForm-從資料庫取值到下拉選單
tags: [C#, 非動態, DropDownList, GridView, Web Form]

---

**最近遇到點選下拉選單並且下拉選單的內容是連動資料表**
如圖(遮一些掉)：
![image](https://hackmd.io/_uploads/BkACVskcp.png)


以下就來分享~
1.先設定成DropDownList
```
 <asp:Label ID="Label18" runat="server" Text="品名："></asp:Label>
 <asp:DropDownList ID="ddlProductNameChi" runat="server" CssClass="tx1_200" Style="width: 220px;" Height="30px" ></asp:DropDownList>  
```
2.以下是**非動態**下拉選單才可以這樣寫喔!!
```
  private string Bind_ddlProductNameChi()
  {
      string ttErrStr = "";
      ttErrStr += down_ddlProductNameChi();
      if (this.UpdatePanel2.UpdateMode == UpdatePanelUpdateMode.Conditional)
      {
          this.UpdatePanel2.Update();
      }

      return ttErrStr;
  }
  //載入內容
  private string down_ddlProductNameChi()
  {
      string ttErrStr = "";

      DataTable ttDw = null;
      System.Web.UI.WebControls.ListItem tmpLa = null;
      // 保存先前選中的值
      string selectedValue = ddlProductNameChi.SelectedValue;

      ddlProductNameChi.Items.Clear();
      try
      {
          ttDw = new DbBillOfMaterials().GetProductNameChi(ssClassPwds);
          ddlProductNameChi.DataSourceID = "";
          ddlProductNameChi.DataSource = ttDw;
          ddlProductNameChi.DataValueField = "ProductCode";
          ddlProductNameChi.DataTextField = "ProductNameChi";
          ddlProductNameChi.DataBind();
          // 恢復先前選中的值
          ddlProductNameChi.SelectedValue = selectedValue;
          tmpLa = new System.Web.UI.WebControls.ListItem();
          tmpLa.Value = "";
          tmpLa.Text = "請選擇";
          ddlProductNameChi.Items.Insert(0, tmpLa);

      }
      catch (Exception ex)
      {
          ttErrStr = "down_ddlProductNameChi-E" + ex.Message;
      }
      return ttErrStr;
  }
```
3.抓資料表的funvtion
```
        public DataTable GetProductNameChi(string ppClassPws)
        {
            DataSet ttDs = new DataSet();

            if (ppClassPws != ssClassPwds)
            {
                DataTable ttDtClear = new DataTable();

                ttDs.Tables.Clear();
                ttDs.Tables.Add(ttDtClear);
                return ttDs.Tables[0];
            }

            string ttSql = string.Empty;
            ttSql = @"
SELECT ProductCode,  ProductNameChi 
FROM   BillOfMaterials
group by all ProductCode , ProductNameChi
";
            ttDs = DataExecute.ExecuteDataset(ssCONN_STRING, CommandType.Text, ttSql);
            return ttDs.Tables[0];
        }
```
4.最後將在Page_Load裡的   if (!this.IsPostBack)中加上
```
 ttErrStr += Bind_ddlProductNameChi();
```
就可以在前端畫面看到資料表的內容啦~~