【发布时间】:2016-09-03 01:38:52
【问题描述】:
我正在尝试从 DataTable 中填充 DataGridView 控件,该控件本身填充了 Oracle 数据库上的 sql 查询结果。这应该在从 ListBox 控件中双击表名后发生。
第一次双击表名时效果很好,但第二次它只会显示列名而没有行。
我发现,根据任何列对 DataGridView 进行排序会导致行突然出现,这让我怀疑某种图形/渲染故障。
这是预期的行为吗?
// event handler for ListBox
private void tables_MouseDoubleClick(object sender, MouseEventArgs e)
{
// tables is a ListBox populated with table names
int index = this.tables.IndexFromPoint(e.Location);
String table_name;
if (index != System.Windows.Forms.ListBox.NoMatches)
{
// reusing the DataTable
dt.Reset();
table_name =tables.Items[index].ToString();
OracleCommand cmd = new OracleCommand();
cmd.Connection = con;
// case sensitive
cmd.CommandText = String.Format(@"select * from ""{0}""",table_name);
cmd.CommandType = CommandType.Text;
OracleDataAdapter da = new OracleDataAdapter(cmd);
da.MissingSchemaAction = MissingSchemaAction.AddWithKey;
da.Fill(dt);
dt.TableName = table_name;
label7.Text = table_name;
// these three lines don't actually accomplish anything in this case
table.DataSource = null;
table.Rows.Clear();
table.DataSource = dt;
// uncommenting these lines produces the expected behavior
//DataGridViewColumn c = table.Columns[0];
//table.Sort(c,System.ComponentModel.ListSortDirection.Descending);
}
}
【问题讨论】:
-
好奇:你为什么不选择更简单的版本:
table_name = tables.SelectedItem.ToString();你是否禁用了列表框?你试过table.Refresh()吗? -
@TaW 感谢您的建议。我确实尝试了 Refresh()、Update() 和其他方法,但排序似乎是唯一有效的方法。此外,ListBox 始终处于启用状态,以便可以选择后续表。
-
嗯,这听起来很奇怪;我确定一定有其他事情发生..您设置的 DGV 的任何其他属性?虚拟模式?
-
尝试使用 BindingSource。
BindingSource source = new BindingSource(); source.DataSource = dt dataGridView.Datasource = source; -
我确实将 Visible 和 Enabled 设置为 false,并且仅在连接到数据库后才将它们设置为 true,但它的行为方式相同。 AutoGenerateColumns 默认设置为 true。我将尝试使用已排序的行,因为排序不会影响 DataTable。
标签: c# winforms datagridview oracle12c