Winform ListView根据条件定位到指定行

 

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 Winfrom
{
    public partial class Form3 : Form
    {
        List<string> list = null;

        public Form3()
        {
            InitializeComponent();

            list = new List<string>();
        }

        private void Form3_Load(object sender, EventArgs e)
        {
            listViewData.Items.Clear();
            listViewData.Columns.Clear();
            listViewData.Columns.Add("选择", 40, HorizontalAlignment.Center);
            listViewData.Columns.Add("序号", 40, HorizontalAlignment.Right);
            listViewData.Columns.Add("运单号", 120, HorizontalAlignment.Center);

            for (int i = 1; i <= 30; i++)
            {
                list.Add(i.ToString());
            }

            foreach (var t in list)
            {
                var row = listViewData.Items.Count + 1;
                var myItem = new ListViewItem();
                myItem.SubItems.Add(row.ToString());
                myItem.SubItems.Add(t);

                if (row % 2 == 0)
                {
                    myItem.BackColor = Color.FromArgb(252, 254, 215);
                }
                myItem.Checked = false;
                listViewData.Items.Add(myItem);
            }
        }

        private void txtWaybillNumber_KeyDown(object sender, KeyEventArgs e)
        {
            if (string.IsNullOrEmpty(txtWaybillNumber.Text.Trim())) return;
            //30
            int index = 0, i = 0;
            foreach (var t in list)
            {
                if (t == txtWaybillNumber.Text.Trim())
                {
                    index = i;
                    break;
                }
                i++;
            }

            listViewData.Items[index].Selected = true;
            listViewData.SelectedItems[0].BackColor = Color.FromArgb(49, 106, 197); 
            listViewData.Items[index].EnsureVisible();
        }
    }
}

 

 

posted @ 2015-12-09 11:39  奇风★逍遥  阅读(3577)  评论(0编辑  收藏  举报