While populating dropdownlist we can pass datatables dataset and we can also pass list for binding
We will create a class for that and defined properties associated with the drpodownlist
/*Entity class containing properties*/
public class Category
{
-- First property named id
public int id
{ get; set; }
-- Second property name
public string name
{ get; set; }
}
Then we will fetch the details and pass this class properties into dropdownlist
public List<Category> GetCategory()
{
DataTable dtcategory = null;
/* To return all the category into the list*/
List<Category> lstCategory = new List<Category>();
try
{
/*Initializing the connection class*/
using (SqlConnection conobj = new SqlConnection(strConnString))
{
/*Initializing the dataadapter class*/
SqlDataAdapter adapgetcategory = new SqlDataAdapter("proc;fillcategory", conobj);
dtcategory = new DataTable(); adapgetcategory.Fill(dtcategory);
foreach (DataRow dr in dtcategory.Rows)
{
lstCategory.Add(new Category()
{
id = Convert.ToInt32(dr["catid"]), name = Convert.ToString(dr["category"]) });
}
}
}
catch (Exception ex)
{
throw ex;
}
return lstCategory; }
After this we will bind it into dropdown directly
/*Checking the list on PageLoad*/
if (!IsPostBack)
{
try
{
/*Filling the dropdown from the function that returned list*/
List<Category> dtcategory = datarepobj.GetCategory();
ddlCategory.DataSource = dtcategory;
ddlCategory.DataTextField = "name";
ddlCategory.DataValueField = "id";
ddlCategory.DataBind();
}
catch (Exception ex)
{
Response.Write(ex.Message);
}
0 Comment(s)