javascript - ASP.Net 中下拉框的数据绑定(bind)

标签 javascript html asp.net drop-down-menu

我必须从名为 dbo.Names 的表中将值(A、B、C、D)放入 SQL Server 的下拉框中。我已经手动完成了此操作,但如何使用 select 语句实现相同的效果从表..???或者如果我必须从存储过程中选择其中包含值的变量???

<div class="col-sm-12">
    <div class="col-sm-4 lhs-form-box" style="padding: 10px; height: 247px;">
        <div class="form-group" style="width: 87%; float: left;">
            <label for="sel1">ITEM</label>
            <asp:DropDownList ID="ddl_QU" runat="server" class="form-control">
                <asp:ListItem Text="A" Value="A"></asp:ListItem>
                <asp:ListItem Text="B" Value="B"></asp:ListItem>
                <asp:ListItem Text="C" Value="C></asp:ListItem>
                <asp:ListItem Text="D" Value="D"></asp:ListItem>
            </asp:DropDownList>
        </div>
        <span>
            <img src="info.png" style="margin: 31px 0px 0px 5px">
        </span>
    </div>
</div>

最佳答案

DropDownList1.Items.Add(new ListItem("Select", ""));
    DropDownList1.AppendDataBoundItems = true;
    String strConnString = ConfigurationManager.ConnectionStrings["your connection"].ConnectionString;
    String strQuery = "SELECT ID, Name FROM YourTable";
    SqlConnection con = new SqlConnection(strConnString);
    SqlCommand cmd = new SqlCommand();
    cmd.CommandType = CommandType.Text;
    cmd.CommandText = strQuery;
    cmd.Connection = con;
    try
    {
        con.Open();
        DropDownList1.DataSource = cmd.ExecuteReader();
        DropDownList1.DataTextField = "Name";
        DropDownList1.DataValueField = "ID";
        DropDownList1.DataBind();
    }
    catch (Exception ex)
    {
        throw ex;
    }
    finally
    {
        con.Close();
        con.Dispose();
    }

关于javascript - ASP.Net 中下拉框的数据绑定(bind),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43474139/

相关文章:

javascript - jquery 验证插件。生成随机成功消息一次

javascript - 识别刷新和关闭浏览器操作

javascript - 是否可以在实例化后向jstree添加更多选项?

javascript - 社会安全号码输入验证

javascript - Ajax 之后单击按钮后禁用按钮 - ASP.NET MVC5

javascript - NodeJS 回调范围问题

javascript - HTML5数据属性为空,但是javascript不同意这种情况

html - 隐藏 :before on :hover button

asp.net - 在 Windows Server 2008 上的 ASP.NET 中使用 Microsoft.Ink

asp.net - 绘制html表头