2017-07-21 9 views
0

前のリストボックスでアイテムがクリックされた後にのみ表示される複数のリストボックスを作成したいとします。リストボックス1のアイテムを選択すると、リストボックス2のアイテムが表示されます。リストボックス2のアイテムをクリックすると、リストボックス3のすべてのアイテムが表示されます。リストボックス1のアイテムをクリックしてリストボックス2を表示しますしかしその後、次のエラーが発生します。オブジェクト参照がオブジェクトのインスタンスに設定されていない。複数のリストボックスを表示するにはどうしたらいいですか?現在選択されていないリストボックスのマウスクリックを設定する方法は?

private void Form1_Load(object sender, EventArgs e) 
    { 
     listBox1.Items.Add(1); 
     listBox1.Items.Add(2); 
     listBox1.Items.Add(3); 
    } 

    private void Form1_MouseClick(object sender, MouseEventArgs e) 
    { 
     string curItem1 = listBox1.SelectedItem.ToString(); 

     if (curItem1 == "1") 
     { 
      listBox2.Items.Add(1); 

      if(curItem1 == "1") 
      {     
       listBox3.Items.Add(1); 
      } 
      string curItem2 = listBox2.SelectedItem.ToString(); 
      ///This is where I get the error! 
     } 
    } 

答えて

-1

あなたはそれが割り当てられていた前listBox2.SelectedItemを基準にして、問題の単純なlistbox2ののSelectedItemプロパティ割り当てる解決するために、例外を受け取ったThatsなぜ:あなたが必要

string curItem1 = listBox1.SelectedItem.ToString(); 

if (curItem1 == "1") 
{ 
    listBox2.Items.Add(1); 
    listBox2.SelectedItem = 1; 
} 
0

をアイテムを追加した後でアイテムを選択するには:

private void Form1_MouseClick(object sender, MouseEventArgs e) 
    { 
     string curItem1 = listBox1.SelectedItem.ToString(); 

     if (curItem1 == "1") 
     { 
      listBox2.Items.Add(1); 
      listBox2.SelectedIndex = 0; //<= This selects the item 

      if (curItem1 == "1") 
      { 
       listBox3.Items.Add(1); 
      } 
      string curItem2 = listBox2.SelectedItem.ToString(); 
      ///This is where I get the error! 
     } 
    } 

ここでいくつかの小切手、例えば。最初の行は次のようになります。

if (listBox1.SelectedItems.Count == 0) return; 
関連する問題