我在winform应用中有一个文本框和列表框。当我在文本框中键入一个值(即字符串)时,我希望列表框显示数据表中的值,当我从列表框中选择一个特定值时,它将显示在文本框中。
代码:
private void txtIName_TextChanged(object sender, EventArgs e)
{
string constring = "Data Source=.;Initial Catalog=Test;User Id=sa;Password=admin@123";
using (SqlConnection con = new SqlConnection(constring))
{
using (SqlCommand cmd = new SqlCommand("SELECT distinct * FROM Item_Details", con))
{
cmd.CommandType = CommandType.Text;
using (SqlDataAdapter sda = new SqlDataAdapter(cmd))
{
using (dt = new DataTable())
{
sda.Fill(dt);
DataView dv = new DataView(dt);
dv.RowFilter = string.Format("IName Like '%{0}%'", txtIName.Text);
listBox1.Visible = true;
listBox1.DataSource = dv;
}
}
}
}
}
但我在列表框中得到了像“system.data.datarow”的输出。通过调试,我可以在dataview'dv'中看到我想要的行。我在这里失踪了什么?谢谢。
答案 0 :(得分:1)
每次TextChanged
事件触发时,您都不需要加载数据。只需在表单的Load
事件中加载数据,然后在TextChanged
中过滤数据就足够了。然后使用DoubleClick
ListBox
之类的事件设置TextBox
的文字:
private DataTable dataTable = new DataTable();
private void Form1_Load(object sender, EventArgs e)
{
string constring = @"Data Source=.;Initial Catalog=Test;User Id=sa;Password=admin@123";
using (SqlConnection con = new SqlConnection(constring))
{
using (SqlDataAdapter sda = new SqlDataAdapter("SELECT distinct * FROM Item_Details", con))
{
sda.Fill(dataTable);
}
}
this.listBox1.DataSource = new DataView(dataTable);
this.listBox1.DisplayMember = "IName";
this.listBox1.Visible = false;
}
private void txtIName_TextChanged(object sender, EventArgs e)
{
var dv = (DataView)this.listBox1.DataSource;
dv.RowFilter = string.Format("IName Like '%{0}%'", txtIName.Text);
listBox1.Visible = true;
}
private void listBox1_DoubleClick(object sender, EventArgs e)
{
var item = (DataRowView)listBox1.SelectedItem;
if (item != null)
this.txtIName.Text = item["IName"].ToString();
else
this.txtIName.Text = "";
this.listBox1.Visible = false;
}
不要忘记将Form1_Load
,txtIName_TextChanged
和listBox1_DoubleClick
处理程序附加到事件中。
答案 1 :(得分:0)
您必须指定您的DisplayMember,它必须是DataView中的某个Field
listBox1.DisplayMember = "Your Field"
然后你可以接受事件SelectedValueChanged:
listBox1.SelectedValueChanged += new EventHandler(listBox1_SelectedValueChanged);
visual studio为您创建一个事件处理程序
void listBox1_SelectedValueChanged(object sender, EventArgs e)
{
// you get your selected item here
}
希望有所帮助