11

I have a html control select

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

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

Please, do not post answers on how to populate a asp:DropDownList because I already know how to do it, I must use a select control.

2
  • do you prefer JSON or find C# solution not very good? Commented Feb 15, 2013 at 13:28
  • 1
    @enb081 look here for json via wcf stackoverflow.com/questions/2086666/… Commented Feb 15, 2013 at 13:33

7 Answers 7

23

aspx:

  <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();
   }
}
Sign up to request clarification or add additional context in comments.

2 Comments

What is "au_fname" and why to use it?
in this particular case, it'd be a column in the authors table from the QueryString row. So if we had Stephen King, John Grisham, and Emily Bronte as rows in the table, the list would then have options for Stephen, John, and Emily. Text being what is seen, value being the item sent. So I'd probably actually set DataValueField to the equivalent of author_id. Would probably also add a First Name + Last Name result in the query for the DataTextField because what happens when you have Tom Clancy and Tom Brokaw? Could consider adding dates for filtering where name is the same too.
5
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

3 Comments

How can I create the Method that returns data from database as json?
are you using mvc or webforms ?
use this to populate: $('#Select1').append($("<option selected></option>") .attr("value", key) .text(val));
4

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

$.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')
   }
});

Comments

3

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:

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

Comments

2

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> 

Comments

0
            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();
            }

Comments

0
  //Controller 
    public IActionResult Create()
    {
        User user = new User();
        ViewBag.items = new SelectList(db.Professions, "Id", "Name", user.ProfessionId);
        return View();
     }


   //View
    @model DbOneToMore.Data.User
    <select asp-for="ProfessionId" >
            <option selected disabled>Choose</option>
        @foreach (SelectListItem i in ViewBag.Items)
            {
            <option value="@i.Value">
                    @i.Text
                </option>
            }
        </select>

    

Надеюсь помогла [1]: dropdownlist set selected value in MVC3 Razor

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.