2011-09-13 31 views
1
for (int counter = 0; counter < countSelected; counter++) 
     { 
      string groupName = txt_GroupName.Text; 
      //Get GroupID from the created group 
      string GroupIDQueryText = "SELECT GroupID FROM tbl_group WHERE GroupName "; 
      int groupID = Convert.ToInt32(server.performQuery(GroupIDQueryText, groupName, MySqlDbType.VarChar)); 
      //To get User ID 
      string firstName = ListBoxMembers.SelectedItems[counter].Value; 
     } 

這不是返回選定的值,而是返回列表中的第一個人,即使我沒有選擇它。我哪裏錯了? System.Web.UI.WebControls不包含defenition爲listboxmembers.selectedItems錯誤從ListBox屬性(C#)中選擇的項目出錯?

+5

在循環內部執行查詢確實不是一個好主意,因爲這會嚴重影響性能。最好先收集所有的ID,然後在一個查詢中使用它們。 –

+0

@Frederik Gheysels多數民衆贊成非常真實! – nawfal

回答

4

您正在使用.Items這是ListBox中所有項目的集合。我想你打算使用.SelectedItemsdocumentation on MSDN)。

// When counter = 0, this is the very first item in the listbox 
ListBoxMembers.Items[counter].Value; 

// When counter = 0, this is the first of the selected items in the listbox 
ListBoxMembers.SelectedItems[counter].Value; 

編輯網站列表框控件比的WinForms的ListBox控件不同,因此,瞭解這方面是非常有價值的。以下是來自MSDN的文章how to determine the selected items in a multi-selection list control(向下滾動到多選部分)。這個想法是遍歷所有.Items並檢查每個屬性的.Selected屬性。

+0

System.Web.UI.WebControls不包含listboxmembers.selectedItems的defenition錯誤 – Mark

+0

@Mark我沒有意識到你在WebControls中,所以我的答案是針對WinForms ListBox。看我的編輯。希望能幫助到你。 –

1

我認爲你應該使用ListBox.SelectedValue("Somval");來設置選定值

1

這很簡單:

如果您有多個列表框的成員,像

# | Name | Selected 
0 | a | false 
1 | b | false 
2 | c | true 
3 | d | true 

那麼你for循環與counter = 0選擇進入(0,a,false),而不是在(2,c,true)

string firstName = ListBoxMembers.Items[counter].Value; 

你必須變量counter的值映射到counter+1個選擇項,或使用SelectedItems,由大衛提及。

相關問題