public partial class Form1 : Form
{
DataTable dtblTemp;
public Form1()
{
InitializeComponent();
InitialTable();
FillComboBox();
}
void InitialTable()
{
dtblTemp = new DataTable();
DataColumn dcolId = new DataColumn(“Id”, System.Type.GetType(“System.String”));
dtblTemp.Columns.Add(dcolId);
DataColumn dcolName = new DataColumn(“Name”, System.Type.GetType(“System.String”));
dtblTemp.Columns.Add(dcolName);
}
void FillComboBox()
{
for (int j = 0; j < 10; j++)
{
comboBox1.Items.Add(j.ToString());
}
}
private void Form1_Load(object sender, EventArgs e)
{
for (int i = 0; i < 100; i++)
{
DataRow drowNew = dtblTemp.NewRow();
drowNew[“Id”] =”iD”+ i.ToString();
drowNew[“Name”] = “Name” + i.ToString();
dtblTemp.Rows.Add(drowNew);
}
//绑定到listBox1
listBox1.DisplayMember = “Name”;
listBox1.ValueMember = “Id”;
listBox1.DataSource = dtblTemp;
//绑定到comboBox2
comboBox2.DisplayMember = “Name”;
comboBox2.ValueMember = “Id”;
comboBox2.DataSource = dtblTemp;
}
private void listBox1_SelectedIndexChanged(object sender, EventArgs e)
{
if (listBox1.SelectedIndex != -1)
{
//textBox1.Text = listBox1.SelectedItem.ToString();//System.Data.DataRowView 错误写法
//textBox1.Text = listBox1.SelectedValue.ToString();//求到的是Id的值ValueMember的值
textBox1.Text = listBox1.Text;//DisplayMember值
DataRowView drv = (DataRowView)listBox1.SelectedItem;
textBox1.Text = drv[“Id”].ToString();//求得Id值(ValueMember)值
textBox1.Text = drv[“Name”].ToString();//DisplayMember值
}
}
//直接填充数据
private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
//this.textBox2.Text = this.comboBox1.SelectedText.ToString();//为””
//this.textBox2.Text = this.comboBox1.SelectedValue.ToString();//null异常
//this.textBox2.Text = this.comboBox1.SelectedItem.ToString();//为comboBox中显示的内容
this.textBox2.Text = this.comboBox1.Text;//为comboBox中显示的内容,
}
//绑定到表与直接填充数据值有差别this.comboBox2.SelectedItem.ToString()
private void comboBox2_SelectedIndexChanged(object sender, EventArgs e)
{
if (comboBox2.SelectedIndex!= -1)
{
//this.textBox3.Text = this.comboBox2.SelectedItem.ToString();System.Data.DataRowView 错误写法
//this.textBox3.Text = this.comboBox2.Text;//与直接填充时一样
this.textBox3.Text = this.comboBox2.SelectedValue.ToString();//得到ValueMember的值
DataRowView drv = (DataRowView)comboBox2.SelectedItem;//此时SelectedItem属性是DataRowView对象
//this.textBox3.Text = drv[“Id”].ToString();
this.textBox3.Text = drv[“Name”].ToString();
}
}
}
//当listBox与comboBox都绑定到表时,用法一样,当comboBox绑定到表与直接数据填充时,有区别.
版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 举报,一经查实,本站将立刻删除。
如需转载请保留出处:https://bianchenghao.cn/35449.html