2013-03-21 48 views
1

我已經編寫了將下拉列表綁定到數據集的以下方法。我需要在我的項目中的不同頁面上調用此方法兩次。所以我創建了一個類並將其放入其中,並且我試圖通過創建一個對象來訪問此方法。有無法做到的......將dropdownlist綁定到從函數返回的數據集

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)")); 
    } 

另外,我還能做什麼?這裏有更好的選擇嗎?

回答

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"]; 
+0

無法找到類型或名稱空間數據集。您是否缺少裝配參考或指令...? ---> public Dataset bindddl() – adityawho 2013-03-21 13:27:14

+0

@AdityaNandandar - 你使用System.Data添加了嗎?在班級的頂部? – MuhammadHani 2013-03-21 13:31:00

+0

是的......沒關係,我重新輸入「數據集」並完成了。謝謝...(標記爲答案) – adityawho 2013-03-21 13:32:39