2016-04-16 26 views
0

讓我嘗試在這裏再次...我在ASP.NET Web窗體這裏刪除功能:第一項總是被讀,而不是選擇(高亮)項的列表框中

 //delete a product from the product list 
    protected void btn_Del_Click(object sender, EventArgs e) 
    { 
     int index = lst_Products.SelectedIndex; //<=== this is the code that gets me stumped. 
               //index keeps returning 0 (zero) whether postback or not 

     //Store product cID and FullLine for LINQ compare 
     string pFullLine = lst_Products.Items[index].ToString(); 
     int cID = Convert.ToInt32(lst_Products.Items[index].Value); 

     // Read ViewState 
     List<Product> allProducts = (List<Product>)ViewState["products"]; 

     List<Product> productsfiltered = allProducts 
             .Where(product => product.CategoryId == cID && product.FullLine == pFullLine).ToList(); 

     foreach (Product prodToDelete in productsfiltered) 
     { 
      //delete it. Most of the time this would only be one item, but more than one entry is possible. 
      allProducts.Remove(prodToDelete); 
     } 

     //store modified product list 
     ViewState["products"] = allProducts; 


     //lst_Products.DataBind(); 
     //BindProdData(); 

     //display products 
     ShowProd(); 

     //show cat ID in Product ID textbox (product ID always = Category ID) 
     txt_ProdID.Text = cID.ToString(); 

    } 

在代碼中的箭頭顯示問題發生的位置:lst_Products.SelectedIndex提供了錯誤的索引值,指向列表框中顯示的第一項,lst_Products,它指向索引0而不是索引1(列表框中高亮顯示的條目)。看看下面這張圖:

Code snippets with debugging data and "Existing Products:" lst_Products listbox

我誤解的代碼SelectedIndex部分的目的是什麼?我認爲這是想讀取突出顯示的項目。如果沒有,我能做些什麼來讀取列表框中選定的(突出顯示的)項目?

下面是我的調試數據的代碼進行比較的較小部分:

Smaller code snippet with debugging data embedded

具體而言,我鼠標選索引1中的列表框使其高亮顯示,然後點擊刪除按鈕,但索引取而代之的是0。

所以我的問題是:

  1. 爲什麼指數0,儘管在列表框中我突出指數1「選擇=真」?
  2. 如何選擇索引1(或索引0以外的值),以便通過刪除例程將其刪除?我試圖根據索引從列表框中獲取文本字符串。
  3. 是否有更適合做同樣事情的代碼?

謝謝你的幫助。

+1

如何在列表框中添加項目?它是數據源嗎?或手動添加項目,如listbox.items.add(「一些數據」); –

+0

你在lst_Products.SelectedValue中得到了正確的值嗎? – Mainak

+0

@CST它來自ViewState。這部分代碼也在工作。 –

回答

0

你試過了嗎?

DropDownList1.Items[DropDownList1.SelectedIndex].Value 
+0

試過了。沒有解決。 –

+0

無論如何,這是一個列表框,而不是一個下拉列表。 –

+0

哦,我很抱歉,我沒有看到, –

0

我對Winform上的列表框有同樣的問題 - 列表中的第一個項目是自動選擇的。我先清除選擇列表(VB.NET代碼):

lboxMembershipTypes.SelectedItems.Clear() 

然後,我選擇了在列表框中的項目根據我的數據集選擇的項目:

'check each row in the dataset 

For Each MembershipROW In MyDataset.Tables(0).Rows 

'select this membership type in the listbox 

MembershipType = MembershipROW.Item("MembershipType") 

MembershipIndex = lboxMembershipTypes.FindStringExact(MembershipType) 

'is this membership in our list? 

If (MembershipIndex <> ListBox.NoMatches) Then 

    'is this membership selected? 

    If (MembershipROW.Item("SelectMembership")) Then 

    'select this membership type 

    lboxMembershipTypes.SetSelected(MembershipIndex, True) 

    End If 

End If 

Next 

我做了一個更通用的解決方案而不是簡單地檢查第一個項目是否被選中,如果不是,那麼取消選擇它 - 然而,這也會起作用。

+0

對不起,但我不能讓所有的代碼被突出顯示請注意「For Each ...」是代碼段的開始,底部的「Next」代碼是代碼的結尾。 –

相關問題