我有一个基本表单类,其中包含一个返回DataTable的方法:
protected DataTable GetTableData(string sql, OracleConnection connection)
{
DataTable table = null;
OracleDataAdapter adapter = null;
try
{
table = new DataTable();
adapter = new OracleDataAdapter(sql, connection);
table.Locale = System.Globalization.CultureInfo.InvariantCulture;
adapter.Fill(table);
}
catch (Exception e)
{
MessageBox.Show("An error occurred while trying to process your request:\n\n" + e.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
finally
{
if (null != adapter)
{
adapter.Dispose();
}
}
return table;
}
另一个窗口是它的子类,并按如下方式调用它:
private void LoadViewData(OracleConnection connection)
{
DataTable table = null;
try
{
var sql = "SELECT * FROM " + this.ObjectName;
table = GetTableData(sql, connection);
this.resultBindingSource.DataSource = table;
}
catch (Exception e)
{
MessageBox.Show("An error occurred while trying to process your request:\n\n" + e.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
finally
{
this.sqlEditor.Focus();
}
}
resultBindingSource
是System.Windows.Forms.BindingSource
。它被设置为DataSource
的{{1}}属性。 (表达式System.Windows.Forms.DataGridView
计算数据库中表或视图的名称。)
当我在调试器中运行代码时,我可以看到SQL执行得很好。我可以看到this.ObjectName
包含数据。我可以看到DataTable
控件已正确绑定到数据源,并且我可以通过其DataGridView
属性查看数据表中的数据。但是,控件本身不会显示任何数据。没有行标题或列标题,也不显示任何数据。
我已经尝试了所有我能想到的东西来确定这个问题的原因。此代码的工作原理与另一个表单完全相同。我尝试删除有问题的控件并重新创建它们,但无济于事。我在MSDN上查阅了有关如何正确数据绑定到DataSource
控件的文章。我尝试使用和不使用DataGridView
(这对我来说似乎没有必要,因为这是数据的只读视图)。
我坦率地说出了想法。我可能忽略了一些相当明显的事情。我知道数据绑定有效,因为我之前已经成功完成了它。
任何指向正确方向的人都会非常感激。
答案 0 :(得分:1)
我尝试使用您在此处提到的部分重新创建程序。我实际上并没有从数据表中获取数据,但这无关紧要。这是我做的:
public partial class Form1 : BaseForm
{
BindingSource source = new BindingSource();
public Form1()
{
InitializeComponent();
this.dataGridView1.DataSource = source;
}
private void button1_Click(object sender, EventArgs e)
{
DataTable table = GetDataTable();
this.source.DataSource = table;
}
}
public class BaseForm : Form
{
protected DataTable GetDataTable()
{
DataTable result = new DataTable();
result.Columns.Add("Name");
result.Columns.Add("Age", typeof(int));
result.Rows.Add("Alex", 27);
return result;
}
}
这与你的情况大致相同吗?我没有任何问题。根据你发布的内容,我们应该这样做。你确定你正确地绑定了一切吗?如果可能,发布更多的绑定代码......