C# 如何在asp.net中从数据库中填充“选择”

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/14892599/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-10 13:21:36  来源:igfitidea点击:

How to populate 'select' from database in asp.net

c#asp.nethtmlsql-server

提问by enb081

I have a html control select

我有一个 html 控件 select

 <select id="Select1" runat="server" name="D1">
    <option></option>
 </select>

How can I populate it with data from my SQL Serverdatabase using C#or JavaScript/jQuery/JSON?

如何SQL Server使用C#或用我的数据库中的数据填充它JavaScript/jQuery/JSON

Please, do not post answers on how to populate a asp:DropDownListbecause I already know how to do it, I must use a selectcontrol.

请不要发布有关如何填充 a 的答案,asp:DropDownList因为我已经知道该怎么做,我必须使用select控件。

采纳答案by MikroDel

aspx:

ASP:

  <select id="Select1" runat="server" name="D1">

  </select>

code behind:

后面的代码:

protected void Page_Load(object sender, EventArgs e)
{
   if (!IsPostBack)
   {
      string ConnectString = "server=localhost;database=pubs;integrated security=SSPI";
      string QueryString = "select * from authors";

      SqlConnection myConnection = new SqlConnection(ConnectString);
      SqlDataAdapter myCommand = new SqlDataAdapter(QueryString, myConnection);
      DataSet ds = new DataSet();
      myCommand.Fill(ds, "Authors");

      Select1.DataSource = ds;
      Select1.DataTextField = "au_fname";
      Select1.DataValueField = "au_fname";
      Select1.DataBind();
   }
}

回答by Jai

You can use jsonin ajax, but you have to return as json from the server using some webservice.

您可以json在 ajax中使用,但您必须使用某些 web 服务从服务器返回 json。

$.ajax({
   url:'/path/to/webservice/method',
   type:'POST',
   dataType: 'json',
   success: function(data){
       $.each(data, function(i, item){
          $('<option value="'+item.val+'">'+item.text+'</option>').appendTo('#Select1');
       });
   },
   error: function(){
      console.log('err')
   }
});

回答by Orhan Cinar

function GetItems() {

var items;

    $.getJSON("/api/MethodName/" + id(Optional), function (data) {
        $.each(data, function (key, val) {
            items += "<option value='" + val.id+ "'>" + val.value+ "</option>";    
        });

        var header = '<option value=\'\'>Select...</option>';
        $('#Select1').html(header + items);
    });

};

You can use asp.net webapi for json, it is very easy and fast

你可以使用asp.net webapi for json,非常简单快捷

回答by Orhan Cinar

In code behind:

在后面的代码中:

 string options = string.Empty; 
 using (SqlConnection sql_conn = new SqlConnection(ConfigurationManager.ConnectionStrings["connstr"].ToString()))
        {
            SqlDataAdapter sql_adapter = new SqlDataAdapter("select Value, Name from YourTable", sql_conn);
            DataSet ds = new DataSet();
            sql_adapter.Fill(ds, "TempTable");

            foreach (DataRow row in ds.Tables["TempTable"].Rows)
            {
                options = "<option value='" + row["Value"] + "'>" + row["Name"] + "</option>";
            }
            sql_conn.Close();
           return options;
        }

and then you can use jquery:

然后你可以使用jquery:

$.get(url, function (data) {        
        $('#Select1').html(data);
    });

回答by user2513019

You can use a repeater

您可以使用中继器

<select>
<asp:Repeater ID="Repeater1" runat ="server" DataSourceID="SqlDataSource1">
    <ItemTemplate>
        <option value='<%# Eval("ID")%>'> <%# Eval("ITEMNAME")%></option>
    </ItemTemplate>
</asp:Repeater>
</select> 

回答by Just_Ice

            using (SqlConnection con = new SqlConnection("Data Source = [HostName]; Initial Catalog = CustomerOrders; Integrated Security = true"))
            {
                SqlCommand cmd = new SqlCommand("SELECT Name FROM Customer", con);
                con.Open();

                dropDownList.DataSource = cmd.ExecuteReader();
                dropDownList.DataTextField = "Name";
                dropDownList.DataValueField = "Name";
                dropDownList.DataBind();
            }