listbox的索引问题
1、UI
2、代码
- using System;
- using System.Collections.Generic;
- using System.ComponentModel;
- using System.Data;
- using System.Drawing;
- using System.Linq;
- using System.Text;
- using System.Threading.Tasks;
- using System.Windows.Forms;
- namespace WindowsFormsApplication8
- {
- public partial class Form1 : Form
- {
- public Form1()
- {
- InitializeComponent();
- }
- /// <summary>
- /// 显示当前的listbox的索引值
- /// </summary>
- /// <param name="sender"></param>
- /// <param name="e"></param>
- private void button3_Click(object sender, EventArgs e)
- {
- MessageBox.Show(listBox1.SelectedIndex.ToString());
- }
- /// <summary>
- /// 让蓝条向上,循环移动
- /// </summary>
- /// <param name="sender"></param>
- /// <param name="e"></param>
- private void buttonShang_Click(object sender, EventArgs e)
- {
- if(listBox1.SelectedIndex==0)
- {
- listBox1.SelectedIndex = listBox1.Items.Count-1;
- }
- else
- {
- listBox1.SelectedIndex--;
- }
- }
- /// <summary>
- /// 有了这个默认值,就好像有了参考系一样。简化了很多代码
- /// </summary>
- /// <param name="sender"></param>
- /// <param name="e"></param>
- private void Form1_Load(object sender, EventArgs e)
- {
- //在窗体加载的时候就给Listbox一个默认值吧,这样可以简化代码
- listBox1.SelectedIndex = 0;
- }
- /// <summary>
- /// 让蓝条向下循环移动
- /// </summary>
- /// <param name="sender"></param>
- /// <param name="e"></param>
- private void buttonXia_Click(object sender, EventArgs e)
- {
- if (listBox1.SelectedIndex == listBox1.Items.Count - 1)
- {
- listBox1.SelectedIndex = 0;
- }
- else
- {
- listBox1.SelectedIndex++;
- }
- }
- }
- }
3、效果图