2014-12-04 70 views
0

我有一個組合框填充數據來自數據庫。我需要默認文本如 「請選擇」以在第一次加載頁面時出現在組合框中,並且在您重置頁面時也必須在最上面。當您只打開組合框時,默認文本正在出現。請幫忙使用閱讀器綁定組合框與默認文本

這裏是我如何綁定我的組合框;

private void LoadCombo() 
    { 
     try 
     { 
      oConnection = new SqlConnection(_connectionString); 
      oCommand = new SqlCommand("select * from tbldpt", oConnection); 
      oAdapter = new SqlDataAdapter(oCommand); 
      oConnection.Open(); 
      oDataset = new System.Data.DataSet(); 
      SqlDataReader oReader = oCommand.ExecuteReader(); 

      while (oReader.Read()) 
      {     
       string _Combobox = oReader["Name"].ToString(); 
       cboDepartment.Items.Add(_Combobox); 
      } 
      cboDepartment.Items.Insert(0, "--Select Department--"); 
      oReader.Close(); 
      oConnection.Close(); 
     } 
     catch(Exception ex) 
     { 
     } 

    } 
+0

你怎麼稱呼這個'LoadCombo'方法? – 2014-12-04 10:38:21

+0

public UserList() { LoadCombo(); } – 2014-12-04 10:45:50

+0

插入默認文本後,只需調用cboDepartment.SelectedIndex = 0; – Vanest 2014-12-04 11:00:25

回答

1

試試這個片斷,

cboDepartment.Items.Add("--Select Department--"); 
while (oReader.Read()) 
    {     
    string _Combobox = oReader["Name"].ToString(); 
    cboDepartment.Items.Add(_Combobox); 
    } 
    cboDepartment.selectedIndex=0; 
+0

感謝它的工作方式,我希望它的工作。最後一件事,你有一個想法,當我試圖將int轉換爲字符串時出現此錯誤的原因; 這裏是我的編碼行... 錯誤:「Input is not in the correct format」 int userid = int.Parse(i.SubItems [3] .Text); – 2014-12-04 11:03:11

+0

什麼是「i.subitems []」它是一個組合框?當綁定4個項目時, – 2014-12-04 11:41:17

+0

用於listview控件 – 2014-12-04 11:52:58

0

創建的字符串列表,並與您的組合框結合。

try 
     { 
      oConnection = new SqlConnection(_connectionString); 
      oCommand = new SqlCommand("select * from tbldpt", oConnection); 
      oConnection.Open(); 
      oDataset = new System.Data.DataSet(); 
      SqlDataReader oReader = oCommand.ExecuteReader(); 

      list<string> _combobox=new list<string>(); 
      _combobox.add("--Select Department--"); 

      while (oReader.Read()) 
      {     
       _combobox.Add(oReader["Name"].ToString()); 

      } 
cboDepartment.Datasource=_combobox 

      oReader.Close(); 
      oConnection.Close(); 
     } 
     catch(Exception ex) 
     { 
     }