2014-02-16 62 views
-1

我在那裏後,我將數據插入我的SQL精簡版數據庫combobox1犯規刷新正確顯示數據的問題。我插入我的資料後,我只需調用下面的方法:插入的數據並沒有顯示正確comboBox1

void fillcomboBox1() 
{ 
    if (m_dbConnection != null && m_dbConnection.State == ConnectionState.Closed) 
    { 
     m_dbConnection.Open(); 
    } 

    SQLiteDataAdapter da = new SQLiteDataAdapter("select * from rdpdirectory order by company asc", m_dbConnection); 

    DataTable dt = new DataTable(); 

    da.Fill(dt); 

    for (int i = 0; i < dt.Rows.Count; i++) 
    { 
     comboBox1.Items.Add(dt.Rows[i]["Company"]); 
    } 
    m_dbConnection.Close(); 
} 

我插入的代碼如下所示:

void InsertConnectionDetails() 

    { 
     if (m_dbConnection != null && m_dbConnection.State == ConnectionState.Closed) 
     { 
      m_dbConnection.Open(); 
     } 



     string sql = @"insert into rdpdirectory (company, server, username, password) 
        values (@company, @server, @username,@password)"; 

     SQLiteCommand command = new SQLiteCommand(sql, m_dbConnection); 
     command.Parameters.AddWithValue("@company", txtCompany.Text); 
     command.Parameters.AddWithValue("@server", txtServer.Text); 
     command.Parameters.AddWithValue("@username", txtUserName.Text); 
     command.Parameters.AddWithValue("@password", txtPassword.Text); 

     command.ExecuteNonQuery(); 

     m_dbConnection.Close(); 
     fillcomboBox1(); 
     comboBox1.Refresh(); 
     MessageBox.Show("Done"); 

} 

我認爲這個想法是重新填補數據表和組合框應顯示的值?具體問題是我看到相同值的重複項,但是當我重新啓動應用程序時,正確插入的值顯示。

回答

1

問題:您每次調用fillcomboBox1()方法時都會將項目添加到組合框中。

所以如果你調用fillcomboBox1()方法兩次ComboBox就surley會有重複的項目,你要添加的項目的兩倍。

解決方案:您需要在添加項目之前清除ComboBox中的項目。 您可以使用comboBox1.Items.Clear()方法添加項目到它之前清除從Combobox所有現有項目。

添加以下語句到fillcomboBox1()方法。

comboBox1.Items.Clear(); 

完整代碼:

void fillcomboBox1() 
{ 
comboBox1.Items.Clear();// <---Add this statement 
if (m_dbConnection != null && m_dbConnection.State == ConnectionState.Closed) 
{ 
    m_dbConnection.Open(); 
} 

SQLiteDataAdapter da = new SQLiteDataAdapter("select * from rdpdirectory order by company asc", m_dbConnection); 

DataTable dt = new DataTable(); 

da.Fill(dt); 

for (int i = 0; i < dt.Rows.Count; i++) 
{ 
    comboBox1.Items.Add(dt.Rows[i]["Company"]); 
} 
m_dbConnection.Close(); 
} 
+0

我該從哪裏補充, ? – PriceCheaperton

+0

@PriceCheaperton:檢查我編輯的答案 –

1

綁定的comboBox1如下

void fillcomboBox1() 
{ 
    // your code ..... 

    da.Fill(dt); 
    comboBox1.DataSource = dt; // set DataSource as your DataTable 
    comboBox1.DisplayMember = "Company"; // you only need to set the display column name 
    m_dbConnection.Close(); 
} 

否則,你需要清除的項目befor增加新的項目