2017-09-14 32 views
0

顯示在組合框沒有數據,更改兩個屬性 AutoCompleteMode ---- SuggestAppend和AutoCompleteSource --- CustomeSource碼是什麼我想組合框AutoCompleteCustomSource C#

SqlDataAdapter da = new SqlDataAdapter("SELECT Pname FROM product", con); 

DataSet ds = new DataSet(); 
da.Fill(ds); 

DataRow row = ds.Tables[0].NewRow(); 
row["Pname"] = -1; 
row["Pname"] = "select Product"; 
ds.Tables[0].Rows.InsertAt(row, 0); 
AutoCompleteStringCollection mycol = new AutoCompleteStringCollection(); 
DataTableReader dr = ds.Tables[0].CreateDataReader(); 
while(dr.Read()) 
{ mycol.Add(dr.GetString(0)); 
} 
comboBox1.AutoCompleteCustomSource = mycol; 
con.Close(); 

AutoCompleteStringCollection對象擁有所有的項目,但組合框顯示沒有

+0

你爲什麼這麼辛苦地完成一項簡單的任務? – Khan

+0

PLZ建議任何其他方式顯示組合框中的項目與自動完成 – zeeshan

+0

我已經更新了答案...現在檢查它。 – Khan

回答

0

您需要設置這些屬性:

comboBox1.AutoCompleteMode = AutoCompleteMode.SuggestAppend; 
comboBox1.AutoCompleteSource = AutoCompleteSource.CustomSource; 

下面是完整的代碼。

AutoCompleteStringCollection mycol = new AutoCompleteStringCollection { 
     "Select product" 
    }; 
    using (SqlConnection con = createconnection()) { 
     using (SqlCommand cmd = new SqlCommand ("SELECT Pname FROM product")) { 
      using (SqlDataReader reader = cmd.ExecuteReader()) { 
       while (reader.Read()) { 
        mycol.Add (Convert.ToString (reader[0])); 
       } 
      } 
     } 
    } 

    comboBox1.AutoCompleteMode = AutoCompleteMode.SuggestAppend; 
    comboBox1.AutoCompleteSource = AutoCompleteSource.CustomSource; 
    comboBox1.AutoCompleteCustomSource = mycol; 

編輯: 我想你想顯示在下拉,而不是自動完成的項目。在這種情況下,您需要添加項目。

comboBox1.Items.Add("Select product"); 
    using (SqlConnection con = createconnection()) { 
     using (SqlCommand cmd = new SqlCommand ("SELECT Pname FROM product")) { 
      using (SqlDataReader reader = cmd.ExecuteReader()) { 
       while (reader.Read()) { 
        comboBox1.Items.Add (Convert.ToString (reader[0])); 
       } 
      } 
     } 
    } 
+0

已經設置這些屬性 – zeeshan

+0

請參閱編輯..這應該工作... – Khan

+0

謝謝它的作品 – zeeshan