답변됨 ListBox button navigation

  • 2012년 3월 13일 화요일 오후 3:13
     
     

    Hello.

    I'm currently doing a school project making my own program.

    In the program I have a ListBox with eight items and only one at a time needs to be selected.

    The difficult part (i think) is that i want to navigate the selection of items, using an up button and a down button.

    I'm pretty new to C# programming, but internet searches give me no results. I'm not sure if this is so simple that I look like an idiot or that no one has ever done this before, which I doubt.

    Thanks in advance.

모든 응답

  • 2012년 3월 13일 화요일 오후 3:22
     
     답변됨

    You need to change the value of SelectedIndex property of ListBox, that holds the index of the selected item.

    In the Up button decrease the value, and in the Down button increase it.


    Marco Minerva [MCPD]
    Blog: http://blogs.ugidotnet.org/marcom
    Twitter: @marcominerva

  • 2012년 3월 13일 화요일 오후 3:25
     
     답변됨 코드 있음

    Up and Down

                if (listBox1.SelectedIndex >= 0 && ((listBox1.SelectedIndex + 1) < listBox1.Items.Count))
                {
                    listBox1.SelectedIndex = listBox1.SelectedIndex + 1;    
                }
                if (listBox1.SelectedIndex > 0 && ((listBox1.SelectedIndex - 1) >= 0))
                {
                    listBox1.SelectedIndex = listBox1.SelectedIndex - 1;
                }


  • 2012년 3월 13일 화요일 오후 3:30
     
     답변됨 코드 있음

    This should give you a good start:

      private void UpButton_Click(object sender, EventArgs e)
      {
       if (listBox1.SelectedIndex == -1)
       {
        if (listBox1.Items.Count > 0)
        {
         listBox1.SelectedIndex = listBox1.Items.Count - 1;
        }
       }
       else
       {
        if (listBox1.SelectedIndex != 0)
        {
         listBox1.SelectedIndex--;
        }
       }
      }
    
      private void DownButton_Click(object sender, EventArgs e)
      {
       if (listBox1.SelectedIndex == -1)
       {
        if (listBox1.Items.Count > 0)
        {
         listBox1.SelectedIndex = 0;
        }
       }
       else
       {
        if (listBox1.SelectedIndex != listBox1.Items.Count - 1)
        {
         listBox1.SelectedIndex++;
        }
       }
      }
    


    It would be greatly appreciated if you would mark any helpful entries as helpful and if the entry answers your question, please mark it with the Answer link.

  • 2012년 3월 13일 화요일 오후 4:06
     
     
    Thanks. This is exactly the solution I was looking for.