Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 951
enb081 Avatar asked Feb 15 '13 10:02

enb081


2 Answers

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')
   }
});
like image 53
Jai Avatar answered Oct 21 '22 09:10

Jai


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();
   }
}
like image 32
MikroDel Avatar answered Oct 21 '22 09:10

MikroDel