jbab8 jbab8 - 17 days ago 5
C# Question

Pass dropdown list into a method

I have the following code

LoadRegistrations();
to populate a
DropDownList
with values from a SQL database.

I will be likely to use this several times in different places so wanted to write a method to take care of it, instead of copying this method and changing minor details.

I've got as far as populating the
DataTable
but I'm not sure how to go about passing a
DropDownList
& the
DataTextField
+
DataValueField
into it and binding the data. Please explain what I have to do

Original Method

private void LoadRegistrations()
{
DataTable reg = new DataTable();
using (SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["ConnString1"].ToString()))
{
try
{
SqlDataAdapter adapter = new SqlDataAdapter("select vehicleID, regNo from dbo.Vehicles order by regNo Asc", con);
adapter.Fill(reg);
ddreg.DataSource = reg;
ddreg.DataTextField = "regNo";
ddreg.DataValueField = "vehicleID";
ddreg.DataBind();
}
catch (Exception ex)
{
// Error handling to be done
}

}
}


New Method

private DataTable PopulateDropdown(string connectionString, DataTable datatable, string query)
{
DataTable dt = new DataTable();
using (SqlConnection con = new SqlConnection(connectionString))
{
try
{
SqlDataAdapter adapter = new SqlDataAdapter(query, con);
adapter.Fill(dt);
//What do I do here? I want to bind to a dropdown list passed into this method
}
catch (Exception ex) { }
}
return dt;
}


ASP to generate dropdown

<asp:DropDownList ID="ddreg" CssClass="form-control" runat="server" AppendDataBoundItems="true">
<asp:ListItem Text="<Select Registration Number>" Value="0" />
</asp:DropDownList>

Answer

You've created a method with parameters:

private DataTable PopulateDropdown(string connectionString, DataTable datatable, string query)

If you want to pass a DropDownList to that method, do exactly what you already do and add a parameter:

private DataTable PopulateDropdown(string connectionString, DataTable datatable, string query, DropDownList myDropDownList)

Then in the method you can refer to myDropDownList:

myDropDownList.DataSource = dt;
myDropDownList.DataBind();

When calling the method, you'd pass it the DropDownList you want to modify:

PopulateDropDown(someConnectionString, someDataTableYouDoNotUse, someQuery, ddreg);
Comments