[ASP.NET][C#][DropDownList]從資料庫讀取資料,建立DropDownList項目(用程式,不使用DataSource控制項)

  • 1563
  • 0

.

.aspx頁面: 

<asp:DropDownList ID="ddlCustomer" runat="server" AppendDataBoundItems="false">
</asp:DropDownList>

 .cs程式碼:

protected void Page_Load(object sender, EventArgs e)
{
	if (!IsPostBack)
	{
		BindDropDownList();
	}
}


private void BindDropDownList()
{
	string sql = string.Empty;

	sql = @" --查客戶清單
				SELECT 
					CustID,
					CustName
				FROM 
					CustInfo 
				ORDER BY CustName; ";

	#region這裡請用自己存取資料庫的方法來執行SQL
    DBTool db = new DBTool();
	DataTable dt = db.ExecuteDataTable(db_connname, sql);
    #endregion

	DataRow ndr = dt.NewRow();
	ndr["CustID"] = "*";
	ndr["CustName"] = "不限";
	dt.Rows.InsertAt(ndr, 0);

	ddlCustomer.DataSource = dt;
	ddlCustomer.DataTextField = "CustName";
	ddlCustomer.DataValueField = "CustID";
	ddlCustomer.DataBind();
}