111,130
社区成员
发帖
与我相关
我的任务
分享
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Data.SqlClient;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Text.RegularExpressions;
using System.Runtime.InteropServices;
using System.Net;
namespace WindowsFormsApplication1
{
public partial class Form2 : Form
{
public Form2()
{
InitializeComponent();
}
//初始化 comboBox1 的列表
private void button1_Click( object sender, EventArgs e )
{
comboBox1.Items.Add( new Simple( "aaa", 0 ) );
comboBox1.Items.Add( new Simple( "bbb", 1 ) );
comboBox1.Items.Add( new Simple( "ccc", 2 ) );
comboBox1.Items.Add( new Simple( "ddd", 3 ) );
comboBox1.Items.Add( new Simple( "eee", 4 ) );
}
//初始化 listBox1 的列表
private void button2_Click( object sender, EventArgs e )
{
listBox1.Items.Add( new Simple( "aaa", 0 ) );
listBox1.Items.Add( new Simple( "bbb", 1 ) );
listBox1.Items.Add( new Simple( "ccc", 2 ) );
listBox1.Items.Add( new Simple( "ddd", 3 ) );
listBox1.Items.Add( new Simple( "eee", 4 ) );
}
//显示 comboBox1 选中项目的内容
private void button3_Click( object sender, EventArgs e )
{
if ( comboBox1.SelectedItem == null )
{
return;
}
Simple k = (Simple)comboBox1.SelectedItem;
MessageBox.Show( k.name + " " + k.index.ToString() );
}
//显示 listBox1 选中项目的内容
private void button4_Click( object sender, EventArgs e )
{
if ( listBox1.SelectedItem == null )
{
return;
}
Simple k = (Simple)listBox1.SelectedItem;
MessageBox.Show( k.name + " " + k.index.ToString() );
}
}
/// <summary>
///
/// </summary>
public struct Simple
{
public string name;
public int index;
public Simple( string n, int i )
{
name = n;
index = i;
}
//重点是重写 ToString 方法,
//由于 listBox 和 comboBox 控件 的项目(Item)都是object,
//所以listBox 和 comboBox 控件显示项目内容时,
//都是取项目的ToString()的结果
public override string ToString()
{
//return name;
//也可以显示成
return index.ToString() + " " + name;
}
}
}
ComboBox.DataSource=DataTable1;
ComboBox.DisplayMember = "id";//显示
ComboBox.ValueMember = "数值";
ComboBox.DataBind();
ComboBox.DisplayMember = "DeptName";//显示
ComboBox.ValueMember = "DeptId";//实际