2017-10-17 66 views
-1

如何存儲我的複選框列表的選中項目?我沒有一個類,所以我不能使用ListItems。我的複選框列表填充使用我的數據庫(MS Access)。如何將複選框項目存儲到C#中的字符串數組?

connection.Open(); 
OleDbCommand command = new OleDbCommand(); 
command.Connection = connection; 
command.CommandText = @"SELECT CONTENT FROM " + tab + " GROUP BY CONTENT ORDER BY MIN(CHAP)"; 
OleDbDataAdapter dAdap = new OleDbDataAdapter(command); 
DataSet dSet = new DataSet(); 
dAdap.Fill(dSet); 
for (int i = 0; i < dSet.Tables[0].Rows.Count; i++) 
{ 
    chkList.Items.Add(dSet.Tables[0].Rows[i][0].ToString()); //This is the part where the items are populated 
} 
connection.Close(); 

編輯使用的foreach

foreach (string chk in chkList.CheckedItems) 
{ 
    MessageBox.Show(chk.ToString()); //This gets every string checked, but one after another 
    top = chk; 
} 

我查詢

"SELECT TOP " + num + " QUESTION,C1,C2,C3,C4,ANSWER,CONTENT FROM " + tab + " WHERE CONTENT = '" + top + "'" 

它只能查詢最後一項檢查。

編輯計數物品託運

MessageBox.Show(chkList.CheckedItems.Count.ToString()); 

string[] topic = new string[chkList.CheckedItems.Count]; 
for (int i = 0; i < topic.Length; i++) 
{ 
    topic[i] = //How to get the text for each checked items?     
} 
+0

你得到任何數據從您的數據庫? – Sasha

+0

那麼,你的代碼真正的問題是什麼? – Ferus7

+0

@Sasha,當我使用combox時,是的,我可以獲取數據。但我會將其更改爲清單,以便我可以選擇多個數據。問題是我不知道如何獲得檢查的項目。我想如果我可以將字符串/ s存儲到數組中並加入它。或者還有其他方法嗎? –

回答

-1

也許這可以幫助你:

connection.Open(); 
OleDbCommand command = new OleDbCommand(); 
command.Connection = connection; 
command.CommandText = @"SELECT CONTENT FROM " + tab + " GROUP BY CONTENT ORDER BY MIN(CHAP)"; 
OleDbDataAdapter dAdap = new OleDbDataAdapter(command); 
DataSet dSet = new DataSet(); 
dAdap.Fill(dSet); 
string[] chkList = new string[dSet.Tables[0].Rows.Count] 
for (int i = 0; i < dSet.Tables[0].Rows.Count; i++) 
{ 
    chkList[i]=dSet.Tables[0].Rows[i][0].ToString(); //This is the part where the items are populated 
} 
connection.Close(); 
+1

我猜chkList已經存在,這不會編譯? – Ferus7

+0

請您指出*如何*和*爲什麼*這解決了OP的問題?只是粘貼一些代碼並不能很好地解決問題。 –

+0

糾正我,如果我錯了。 string [] chkList = new string [dSet.Tables [0] .Rows.Count]將創建一個數組的行數?如果項目被檢查,這也會得到嗎? –

相關問題