c# - What is the way to populate a dropdownlist from a database in asp.net by using classes? -
i trying populate dropdownlist sql server using classes shown below. code breaks down when comes bind data dropdown list. gives error on giving dropdownlist datavaluefield , datattextfield.
html... a.aspx
<asp:dropdownlist id="nationalitydropdownlist" runat="server" > </asp:dropdownlist> c#... a.aspx.cs
protected void page_load(object sender, eventargs e) { classes.nationality possiblenationality = new classes.nationality(); if (!page.ispostback) { datatable datatable = possiblenationality.getnationality(); nationalitydropdownlist.datasource = datatable; nationalitydropdownlist.datavaluefield = "id"; nationalitydropdownlist.datatextfield = "nationality"; nationalitydropdownlist.databind(); } } nationality.cs
public class nationality { public datatable getnationality() { sqlconnection conn; sqlcommand comm; string connectionstring = configurationmanager.connectionstrings["informationconnection"].connectionstring; conn = new sqlconnection(connectionstring); comm = new sqlcommand("spgetallusers", conn); comm.commandtype = commandtype.storedprocedure; datatable datatable; try { conn.open(); sqldataadapter da = new sqldataadapter(); da.selectcommand = comm; datatable = new datatable(); da.fill(datatable); } { conn.close(); } return datatable; } } sql procedure....
alter procedure [dbo].[spgetnationalities] begin select * nationality; end
this line of code in getnationalitymethod...
comm = new sqlcommand("spgetallusers", conn); ...should instead
comm = new sqlcommand("spgetnationalities", conn); databinding should work if nationality table has columns id , nationality
Comments
Post a Comment