【发布时间】:2017-06-09 09:44:02
【问题描述】:
我有一个组合框,可以从选择中检索数据,还有一个 datagridview 可以从另一个查询中检索数据。我想使用组合框值过滤数据网格视图。我正在尝试一切,但没有任何效果。能否请你帮忙?此外,为什么当我声明 dataview=((DataTable)datagridview.datasource.defaultview (combobox_SelectedIndexChanged 中的第一行)时,我再也看不到组合框中的任何值,而是看到 System Data DataRowView 但第一个问题对我来说更重要
private void Form5_Load(object sender, EventArgs e)
{
SqlConnection conn = new SqlConnection(@"Data Source=xxxxx;Initial Catalog=xxxxx;Integrated Security=True;");
conn.Open();
SqlCommand sc = new SqlCommand(" SELECT id, customername+' - '+cast(inserted as varchar(19)) as targ FROM bf where customername>'a' order by customername asc, inserted desc ", conn);
SqlDataReader reader;
reader = sc.ExecuteReader();
DataTable dt = new DataTable();
dt.Columns.Add("id", typeof(string));
dt.Columns.Add("targ", typeof(string));
dt.Load(reader);
comboBox1.ValueMember = "id";
comboBox1.DisplayMember = "targ";
comboBox1.DataSource = dt;
conn.Close();
var select = "SELECT [id],[CustomerName[email],[Capital] FROM baf order by id desc";
var c = new SqlConnection("Data Source=xxxxxx;Initial Catalog=xxxxx;Integrated Security=True;"); // Your Connection String here
var dataAdapter = new SqlDataAdapter(select, c);
var commandBuilder = new SqlCommandBuilder(dataAdapter);
var ds = new DataSet();
dataAdapter.Fill(ds);
dataGridView1.ReadOnly = true;
dataGridView1.DataSource = ds.Tables[0];
}
private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
//var dataView = ((DataTable)dataGridView1.DataSource).DefaultView;
// if (comboBox1.Text == "Remove filter")
// {
// dataView.RowFilter = string.Empty;
// }
// else
// {
// //dataView.RowFilter = "id = {comboBox1.Text}";
// }
//}
}
【问题讨论】:
-
尝试这种方式: private void comboBox1_SelectedIndexChanged(object sender, EventArgs e) { DataView dv = dataGridView1.DataSource as DataView; dv.RowFilter="id=[ComboBox1.Text]";给我错误对象引用未设置为对象的实例。并在组合框中显示系统数据 DataRowView
-
如果您尝试在 RowFilter 上使用字符串插值,您需要在前面加上一个美元符号:
$"id = {comboBox1.Text}"但是,您可能应该使用SelectedValue,而不是Text。 -
private void comboBox1_SelectedIndexChanged var dataView = ((DataTable)dataGridView1.DataSource).DefaultView; if (comboBox1.Text == "删除过滤器") { dataView.RowFilter = string.Empty; } else { dataView.RowFilter = $"id = {comboBox1.SelectedValue}";错误意外字符,加上只有赋值调用,增量,减量和新对象可以用作语句,无效的表达式术语''}
-
什么版本的 Visual Studio?如果您不进行字符串插值,那么您必须从引号中取出组合框属性访问权限。
-
VS 2010 专业版。将属性访问权限从报价单中删除是什么意思?
标签: c# winforms datagridview combobox