Reputation: 1242
I have written the following method that binds the dropdown to the dataset. I need to call this method twice in my project on different pages. So I created a class and put the method in it and I am trying to access this method by creating an object. Having trouble doing so...
public void bind()
{
DataSet ds1 = new DataSet();
SqlConnection con = new SqlConnection(System.Configuration.ConfigurationManager.AppSettings["ConnectionString"]);
con.Open();
string strQuery = "SELECT CountryName + '(+' + CountryCode + ')' As CountryName,CountryCode from ACountry";
SqlCommand cmd = new SqlCommand(strQuery, con);
using (SqlDataAdapter da = new SqlDataAdapter(cmd))
da.Fill(ds1, "AUser");
ddlCountryCode.DataSource = ds1.Tables["AUser"];
ddlCountryCode.DataTextField = "CountryCode";
//ddlCountryCode.SelectedValue = "India(+91)";
ddlCountryCode.DataBind();
ddlCountryCode.SelectedIndex = ddlCountryCode.Items.IndexOf(ddlCountryCode.Items.FindByText("India(+91)"));
con.Close();
}
If I write this complete method in the new class, it does not recognize the controls (the dropdownlist) used in it & so it throws an error. So I included only the following part in it:
public void bindddl()
{
DataSet ds1 = new DataSet();
SqlConnection con = new SqlConnection(System.Configuration.ConfigurationManager.AppSettings["ConnectionString"]);
con.Open();
string strQuery = "SELECT CountryName + '(+' + CountryCode + ')' As CountryName,CountryCode from ACountry";
SqlCommand cmd = new SqlCommand(strQuery, con);
using (SqlDataAdapter da = new SqlDataAdapter(cmd))
da.Fill(ds1, "AUser");
con.Close();
}
now this returns a dataset that I need to bind with the dropdown list on another form (.aspx). How do I do that?
protected void Page_Load(object sender, EventArgs e)
{
Bind objbind = new Bind();
ddlCountryCode.DataSource = objbind.---->?????????;
ddlCountryCode.DataTextField = "CountryCode";
//ddlCountryCode.SelectedValue = "India(+91)";
ddlCountryCode.DataBind();
ddlCountryCode.SelectedIndex = ddlCountryCode.Items.IndexOf(ddlCountryCode.Items.FindByText("India(+91)"));
}
Also, What else can I do? Is there another better option here?
Upvotes: 1
Views: 18354
Reputation: 8664
Make your function returns DataSet then assign it to whatever you want
public DataSet bindddl()
{
DataSet ds1 = new DataSet();
SqlConnection con = new SqlConnection(System.Configuration.ConfigurationManager.AppSettings["ConnectionString"]);
con.Open();
string strQuery = "SELECT CountryName + '(+' + CountryCode + ')' As CountryName,CountryCode from ACountry";
SqlCommand cmd = new SqlCommand(strQuery, con);
using (SqlDataAdapter da = new SqlDataAdapter(cmd))
da.Fill(ds1, "AUser");
con.Close();
return ds1;
}
Then assign them as below.
Bind objbind = new Bind();
ddlCountryCode.DataSource = objbind.bindddl().Tables["AUser"];
Upvotes: 1