using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace COMM.Type
{
//给ComboBox的每一行附加tag的操作
static public class CmbItemTag
{
//当前选择的数据的tag
static public T GetCurrentTag<T>(System.Windows.Forms.ComboBox cmb)
{
return (T)((TextTag)(cmb.SelectedItem)).Tag;
}
//通过tag选择数据
static public void SetCurrentDataByTag<T>(ComboBox cmb, Func<T, bool> funCmp)
{
foreach (var item in cmb.Items)
{
if (funCmp(((TextTag)item).GetTag<T>()))
{
cmb.SelectedItem = item;
break;
}
}
}
}
}
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
for (int i = 0; i < 10; i++)
{
COMM.Type.TextTag item = COMM.Type.TextTag.CreateNew("t" + i.ToString(), i);
comboBox1.Items.Add(item);
}
}
private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
textBox1.Text = COMM.Type.CmbItemTag.GetCurrentTag<int>(comboBox1).ToString();
}
private void button1_Click(object sender, EventArgs e)
{
COMM.Type.CmbItemTag.SetCurrentDataByTag<int>(comboBox1, (t) => t == Convert.ToInt32(textBox2.Text));
}
}