星期一, 9月 22, 2014

[C#] ListBox 基本操作

整理 ListBox 的基本操作
namespace WindowsFormsApplication1
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            // 建立 ListBox 內的資料來源
            lstData.Items.Add("111");
            lstData.Items.Add("222");
            lstData.Items.Add("333");
            lstData.Items.Add("444");
            lstData.Items.Add("555");
        }

        private void btnAdd_Click(object sender, EventArgs e)
        {
            string content = txtContent.Text.Trim();
            if (string.IsNullOrEmpty(content)) return ;
            lstData.Items.Add(content);
        }

        private void btnTruncate_Click(object sender, EventArgs e)
        {
            lstData.Items.Clear();
        }

        private void btnModify_Click(object sender, EventArgs e)
        {
            string NewData = txtContent.Text.Trim();
            if (string.IsNullOrEmpty(NewData)) return;

            int index = lstData.SelectedIndex;
            if (index == -1) return;

            lstData.Items[index] = NewData;
        }

        private void btnDelete_Click(object sender, EventArgs e)
        {
            int index = lstData.SelectedIndex;
            if (index == -1) return;
            lstData.Items.RemoveAt(index);
        }

        private void btnSearch_Click(object sender, EventArgs e)
        {
            if (lstData.Items.Count == 0) return;

            string search = txtSearch.Text.Trim();
            if (string.IsNullOrEmpty(search)) return;

            int index = lstData.FindStringExact(search);
            if (index == -1)
            {
                MessageBox.Show("ListBox 內沒有該項目");
            }
            else
            { 
                lstData.SelectedIndex = index;
            }
        }
    }
}
[C#] ListBox 基本操作

沒有留言:

張貼留言