0

在这里,我绑定了一个 ddl 来填充如下值:Australis(+61)。在另一个地方,我想绑定另一个 ddl 来填充这样的值:澳大利亚。我可以使用相同的代码并更改查询吗?实际上,我在所需位置(不同的 aspx 页面)调用此函数(在单独的类中定义)。那么我可以避免代码冗余,否则我将不得不重复代码

public DataSet BindDropDownList()
    {
        DataSet ds = 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(ds, "AUser");
        con.Close();
        return ds;
    }

这就是我在其中一个 aspx 页面中调用它的方式:

 protected void Page_Load(object sender, EventArgs e)
    {

        UserFunctions objBindDDL = new UserFunctions();
        ddlCountryCode.DataSource = objBindDDL.BindDropDownList().Tables["AUser"];
        ddlCountryCode.DataTextField = "CountryName";
        ddlCountryCode.DataValueField = "CountryCode";
        //ddlCountryCode.SelectedText = ddlCountryCode.Items.FindByText("India(+91)");
        ddlCountryCode.DataBind();
}

@Praveen:这是我只想要国家名称的地方

    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            UserFunctions objBindDDL = new UserFunctions();
            ddlCountry.DataSource = objBindDDL.BindDropDownList().Tables["AUser"];
            ddlCountry.DataTextField = "CountryName";
            //ddlCountry.DataValueField = "CountryName";
            //ddlCountryCode.SelectedText =  ddlCountryCode.Items.FindByText("India(+91)");
            ddlCountry.DataBind();
        }
    }
4

2 回答 2

1

考虑到您的最后一条评论,这样做非常简单:

您需要CountryName在您的中单独取值,resultset如下所示。

string strQuery = "SELECT CountryName,  CountryName + '(+' + CountryCode + ')' As CountryNameCode, CountryCode from ACountry";

然后每当你绑定你的dropdownlist,你只需要改变DataTextField

 ddlCountryCode.DataTextField = "CountryNameCode";   // For Country name and code
 ddlCountryCode.DataTextField = "CountryName";       // for just country name

你的其余部分code将保持不变。

还有一件重要的事情要注意:
不要dropdownlist直接绑定你的page load. 采用IsPostBack

protected void Page_Load(object sender, EventArgs e)
{

    if(!IsPostBack)
    {
        // your binding here
    }
}
于 2013-03-23T06:27:48.880 回答
1

你只需要使用参数,像这样向这个函数添加新参数。

public DataSet BindDropDownList(Bool IsIndexPage)
    {
        DataSet ds = new DataSet();
        SqlConnection con = new SqlConnection(System.Configuration.ConfigurationManager.AppSettings["ConnectionString"]);
        con.Open();

        string strQuery = "";
if(IsIndexPage)
{
   strQuery = "SELECT CountryName + '(+' + CountryCode + ')' As CountryName,CountryCode from ACountry";
}
else
{
  strQuery = "SELECT CountryName,CountryCode from ACountry";
}
        SqlCommand cmd = new SqlCommand(strQuery, con);
        using (SqlDataAdapter da = new SqlDataAdapter(cmd))
        da.Fill(ds, "AUser");
        con.Close();
        return ds;
    }
于 2013-03-23T06:28:32.087 回答