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.
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')
}
});
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();
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With