2013-05-18 33 views
0

在Visual Studio 2010(使用Visual C#)中,我有一個表單,其中有一個listBox(名爲listBox1)。用戶選擇列表框上顯示的項目之一,然後點擊保存按鈕。該應用程序使用節省了用戶的選擇到數據庫:C#listBox.SelectedIndex來自數據庫

cmd.CommandText = "insert into Table2 (kat) values ('"+listBox1.SelectedIndex.ToString()+"')"

(編輯),例如,它們被保存爲0或1或2等..

然後,我希望應用程序使用即int在另一個列表框上選擇相同的項目,但在另一個窗體上完全相同的項目。

我至今是:

cmd.CommandText = "select * from Table1 WHERE username='"+textBox1.Text+"'"; 
           dr = cmd.ExecuteReader(); 
           if (dr.HasRows) 
           { 
            while (dr.Read()) 
            { 
             form1.listBox1.SelectedIndex(dr[0]); 
            } 

           } 

回答

1

您在數據庫中插入值String,然後試圖將值添加作爲Integer走錯了路

正確插入值作爲整數

cmd.CommandText = "INSERT INTO Table1(kat) VALUES(@id)"; 
cmd.Parameters.AddWithValue("@id", listBox1.SelectedIndex); 
cmd.ExecuteNonQuery(); 

要在其他表單上創建listBox副本,您可以使用SELECT查詢來完成此操作。

Ex。

cmd.CommandText = "SELECT kat FROM Table1"; 

var reader = cmd.ExecuteReader(); 

while(reader.Read()) 
{ 
    otherListBox.Items.Add(reader[0]); 
} 
reader.Close(); 

要同步列表,試試這個

int index = listBox1.FindStringExact("id to find"); 

if (index > -1) 
{ 
    listBox1.SelectedIndex = index; 
} 
+0

也同時從數據庫中讀取,你可以使用'int.parse(DR [0]的ToString());'。 – Saravanan

+0

不需要'Int32.Parse'作爲INT插入值而不是STRING –

+0

我不在乎它們是保存爲int還是字符串(已編輯它)。我不知道如何檢索它們 – Shevliaskovic