4

こんにちは 選択したインデックスの値をリストボックスから変数に割り当てる正しい方法は何ですか? ユーザーがリストボックス内の項目を選択すると、選択に応じて出力が変化します。

私が使う:

variablename = listbox.text

listBox_SelectedIndexChangedイベントで、これは機能します 。

私が使用するbutton_clickイベントを使用するとき:

variablename = listbox.selectedindex 

listbox_selectedindexchangedしかし、これはイベントでは機能しません。

上記のように使用しても問題ないのか、それとも問題が発生するのか、selectedindex メソッドを使用できない理由を教えてください。

ありがとう!

4

2 に答える 2

4

A. 変数が文字列のように聞こえますが、SelectedIndex プロパティによって返される値 (整数) を変数に割り当てようとしています。

B. リストボックスの SelectedINDex に関連付けられたアイテムの値を取得しようとしている場合は、インデックスを使用してオブジェクト自体を返します (リストボックスはオブジェクトのリストであり、多くの場合、常にではありませんが、文字列になります)。 )。

Private Sub ListBox1_SelectedIndexChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles ListBox1.SelectedIndexChanged
    'THIS retrieves the Object referenced by the SelectedIndex Property (Note that you can populate
    'the list with types other than String, so it is not a guarantee that you will get a string
    'return when using someone else's code!):
    SelectedName = ListBox1.Items(ListBox1.SelectedIndex).ToString
    MsgBox(SelectedName)
End Sub

これは、SelectedItem プロパティを使用して、もう少し直接的です。

Private Sub ListBox1_SelectedIndexChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles ListBox1.SelectedIndexChanged

    'This returns the SelectedItem more directly, by using the SelectedItem Property
    'in the event handler for SelectedIndexChanged:
    SelectedName = ListBox1.SelectedItem.ToString
    MsgBox(SelectedName)

End Sub
于 2011-04-03T15:07:26.060 に答える
2

それは、リストボックスの選択されたアイテムから何を達成したいかによって異なります。

考えられる方法がいくつかあります。宿題のために、これらのいくつかを説明してみましょう。

2 つの列とその行を含むデータ テーブルがあるとします。

ID    Title
_________________________
1     First item's title
2     Second item's title
3     Third item's title

そして、このデータ テーブルを次のようにリスト ボックスにバインドします。

ListBox1.DisplayMember = "ID";
ListBox1.ValueMember = "Title";

ユーザーがリスト ボックスから 2 番目の項目を選択した場合。

選択したアイテムの表示値(タイトル)を取得したい場合は、次のことができます

string displayValue = ListBox1.Text;   // displayValue = Second item's title

またはこれでも同じ結果が得られます。

// displayValue = Second item's title
string displayValue = ListBox1.SelectedItem.ToString();

そして、選択したアイテムに対して値のメンバーを取得するには、次のことを行う必要があります

string selectedValue = ListBox1.SelectedValue;    // selectedValue = 2

ユーザーがリスト ボックスから複数の項目を選択できるようにする場合があるため、次のように設定します。

ListBox1.SelectionMode = SelectionMode.MultiSimple;

また

ListBox1.SelectionMode = SelectionMode.MultiExtended;

ここで、ユーザーが 2 つのアイテムを選択したとします。二番目と三番目。

したがって、単に反復するだけで表示値を取得できますSelectedItems

string displayValues = string.Empty;
foreach (object selection in ListBox1.SelectedItems)
{
    displayValues += selection.ToString() + ",";
}

// so displayValues = Second item's title, Third item's title,

ID'sそして、代わりに取得したい場合Title'sは...

私も調べているので、見つけたら追記します。

皆様の理解が深まることを願っています。

幸運を!

于 2011-04-03T15:05:34.327 に答える