将下拉列表绑定到数据库字段

问题描述:

下拉列表或组合框可以直接绑定到数据库字段吗?对于文本框,我可以使用

Can a dropdownlist or combobox be directly bound to a database field? For a text box I can use the

<asp:TextBox ID="TextBox1" runat="server" Text='<%# Bind("Reviewer1Title") %>' />




我尝试使用databindings弹出窗口中的字段绑定,但该字段显示为灰色.




I tried to use the field bindings from the databindings popup but it is greyed out.

使用数据源和数据源id属性,您可以将下拉列表直接绑定到您的数据库.

就像您必须在页面上的sqldatasource控件上声明并使用该sqldatasource控件的ID直接将数据绑定到您的下拉列表

using data source and data source id property you can directly bind your dropdown list to your database.

like you have to declare on sqldatasource control to your page and use the id of that sqldatasource control to directly bind data to your drop down list

<asp:sqldatasource id="CostGroupDataSource" runat="server" selectcommand="SELECT tblCostGroup.costGroupID, tblCostGroup.costGroup FROM tblCostGroup ORDER BY tblCostGroup.costGroup">




<asp:dropdownlist id="ddltest" width="152px" runat="server" datasourceid="CostGroupDataSource" datatextfield="COSTGROUP" datavaluefield="COSTGROUPID" appenddatabounditems="true">
<asp:listitem text="" value="">


string strConn = "Data Source=localhost;uid=sa;pwd=password;Initial Catalog=northwind";
                 SqlConnection mycn = new SqlConnection(strConn);
                 DataSet ds = new DataSet();
                 SqlDataAdapter myda = new SqlDataAdapter("Select * FROM CategoryTable ", mycn);
                 myda.Fill(ds);
                 MyDropDownList.DataSource = ds;
                 MyDropDownList.DataTextField = "CategoryName";
                 MyDropDownList.DataValueField = "CategoryId";
                 MyDropDownList.DataBind();
           }