2010-06-29 49 views
1

使用VS2005和C#填寫組合框中的表值

我想通過使用表值填充組合框。

代碼

OdbcConnection con = new OdbcConnection(); 
    OdbcCommand cmd; 

con.ConnectionString =       ""; 
     con.Open(); 
     cmd = new OdbcCommand("Select no from table", con); 
     ada = new OdbcDataAdapter(cmd); 
     ds = new DataSet(); 
     ada.Fill(ds); 
     combobox1.Items.Add(ds); 

但是,沒有值被裝載在ComboBox,有什麼毛病我上面提到的代碼。

可以在任何提供了萬阿英,蔣達清的解決方案....

回答

0

有你的真實連接字符串中的東西,對不對?

您正在將數據加載到數據集 - 這是表和關係的集合。組合框應該如何知道要顯示哪個表格的數據?如果DataSet中包含多個表格,則必須額外定義要使用哪一個表格。如果DataSet裏面只有一個表格,那麼首先使用DataSet會浪費資源。

如果你只有一組數據,使用一個DataTable代替:

con.Open(); 
cmd = new OdbcCommand("Select no from table", con); 
ada = new OdbcDataAdapter(cmd); 
DataTable data = new DataTable(); 
ada.Fill(data); 

// define the column to be used to display text in the combobox 
combobox1.DataTextField = "FirstName"; 
// define the column to be used as the value for the selection in the combobox 
combobox1.DataValueField = "CustomerID"; 

combobox1.DataSource = data; 
combobox1.DataBind(); 
+0

在而非顯示值 – Gopal 2010-06-29 05:12:01

+0

@Gopal System.Data.Datarowview組合框:更新了我的答案有兩個額外的任務 – 2010-06-30 06:57:00

+0

@ marc在combobox中有datatextfield n datavaluefield – buddy 2014-07-03 04:47:35