簡體   English   中英

獲取列表框中所選項目的值作為字符串

[英]Getting value of selected item in list box as string

我正在嘗試使用下面的代碼獲取列表框中所選項目的值,但它總是返回空字符串。

DataSet ds = searchforPrice(Convert.ToString(listBox1.SelectedItem));

在這里,我試圖將所選項目的值作為字符串傳遞給方法 searchforPrice 以從數據庫中檢索數據集。

如何將所選項目的值檢索為字符串?

我正在從組合框將項目添加到列表框中,組合框又從數據庫中加載項目。

 listBox1.Items.Add(comboBox2.Text);

在此處輸入圖像描述

任何人都有這個答案..

如果要檢索項目的顯示文本,請使用GetItemText方法:

string text = listBox1.GetItemText(listBox1.SelectedItem);

如果您在應用程序中使用 ListBox 並且想要返回 ListBox 的選定值並將其顯示在標簽或其他任何東西中,然后使用此代碼,它將幫助您

 private void listBox1_SelectedIndexChanged(object sender, EventArgs e)
    {
         label1.Text  = listBox1.SelectedItem.ToString();
    }

要檢索 à listbox 中所有選定項目的值,您可以在 DataRowView 中轉換選定項目,然后選擇數據所在的列:

foreach(object element in listbox.SelectedItems) {
    DataRowView row = (DataRowView)element;
    MessageBox.Show(row[0]);
}
string textValue = ((ListBoxItem)listBox1.SelectedItem).Content.ToString();

如果您想從列表框中檢索您的值,您應該嘗試以下操作:

String itemSelected = numberListBox.GetItemText(numberListBox.SelectedItem);

在文件列表框中獲取 FullName(完整路徑)列表(Thomas Levesque 回答修改,感謝 Thomas):

...
        string tmpStr = "";
        foreach (var item in listBoxFiles.SelectedItems)
        {
            tmpStr += listBoxFiles.GetItemText(item) + "\n";
        }
        MessageBox.Show(tmpStr);
...

你可以使用這個來獲取選中的 ListItme Name::

String selectedItem = ((ListBoxItem)ListBox.SelectedItem).Name.ToString();

確保您的每個 ListBoxItem 都有一個 Name 屬性

詳細說明 Pir Fahim 先前的回答,他是對的,但我使用的是 selectedItem.Text (使其對我有用的唯一方法)

使用 SelectedIndexChanged() 事件將數據存儲在某處。 就我而言,我通常填寫一個自定義類,例如:

class myItem {
    string name {get; set;}
    string price {get; set;}
    string desc {get; set;}
}

private void listBox1_SelectedIndexChanged(object sender, EventArgs e)
{
     myItem selected_item = new myItem();
     selected_item.name  = listBox1.SelectedItem.Text;
     Retrieve (selected_item.name);
}

然后您可以從“myItems”列表中檢索其余數據..

myItem Retrieve (string wanted_item) {
    foreach (myItem item in my_items_list) {
        if (item.name == wanted_item) {
               // This is the selected item
               return item; 
        }
    }
    return null;
}

設置屬性 listbox1 DisplayMember = "Text"; 設置屬性 listbox1 ValueMember = "Value";

事件

    private void listbox1_SelectedIndexChanged(object sender, EventArgs e)
    {
        string selectedValue = listbox1.SelectedValue.ToString();
    }

正確的解決方案似乎是:

string text = ((ListBoxItem)ListBox1.SelectedItem).Content.ToString();

請務必使用.Content而不是.Name

如果您想檢索從列表框中選擇的項目,這里是代碼...

String SelectedItem = listBox1.SelectedItem.Value;

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM