我编写了以下方法,将下拉列表绑定到数据集。我需要在不同页面的项目中调用此方法两次。所以我创建了一个类并将该方法放入其中,我试图通过创建一个对象来访问该方法。无法这样做......
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();
}
如果我在新类中编写这个完整的方法,它将无法识别其中使用的控件(下拉列表)和&所以它抛出一个错误。所以我只在其中包含以下部分:
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();
}
现在返回一个我需要与另一个表单(.aspx)上的下拉列表绑定的数据集。我该怎么做?
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)"));
}
另外,我还能做什么?这里有另一个更好的选择吗?
答案 0 :(得分:1)
让您的函数返回DataSet,然后将其分配给您想要的任何内容
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;
}
然后按如下方式分配。
Bind objbind = new Bind();
ddlCountryCode.DataSource = objbind.bindddl().Tables["AUser"];