2016-04-16 38 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”代码是代码的结尾。 –

相关问题