本文主要是介绍C# ComboBox数据绑定,选定特定项,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
ComboBox 再绑定之后,需要一打开绑定的界面就选定你所需要选定的文本,这就是我今天解决这个问题遇到的
ComboBox 采用DataSource绑定之后,根据原理应该是DataView绑定的,那么其中的每一行数据都是一个DataRowView,今天就是忽略了这一点,才出现了错误:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Data.SqlClient;
namespace comboboxBind
{
public partial class Form1 : Form
{
const string StrCon = @"Data Source=JIANGZHENG711/JIANGZHENG;Initial Catalog=mmcs;Integrated Security=True";
SqlConnection sqlcon = null;
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
DataTable table = new DataTable();
sqlcon = new SqlConnection(StrCon);
SqlDataAdapter ada = new SqlDataAdapter("select top 20 jsyhm,xm from zjsxx", sqlcon);
sqlcon.Open();
ada.Fill(table);
sqlcon.Close();
comboBoxEx1.DataSource = table.DefaultView;
comboBoxEx1.DisplayMember = "xm";
comboBoxEx1.ValueMember = "jsyhm";
}
private void buttonX1_Click(object sender, EventArgs e)
{
for (int i = 0; i < comboBoxEx1.Items.Count; i++)
{
if (((DataRowView)comboBoxEx1.Items[i])[1].ToString().Trim() == textBoxX1.Text.Trim())
{
comboBoxEx1.SelectedIndex = i;
break;
}
this.Text = comboBoxEx1.Items[i].GetType().ToString();
}
}
}
}
这是改正之后的代码,原先没有将comboBoxEx1.Items[i]项转换为DataROwView 怎么都不能使语句判断成立。进入到选定语句,后来已测试才知道,绑定之后的Items的单项就是一行DataRowView,所以比较的时候比较不出来,经过改进这样就可以了!
或者可以直接使用DataTable作为 查找的循环,也不错
这篇关于C# ComboBox数据绑定,选定特定项的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!