我没有使用设计器,而是尝试以编程方式填充我放在 Winform 上的 DataGridView。当我查看调试器下的表格时,它具有正确的列和行数。问题是网格在我的表单上显示为空的灰色框。当我通过 VS 2008 Designer 将网格绑定到数据库时,它工作得很好。我怎样才能找到问题所在?
UPDATE
我几乎从这个中得到了这个MSDN 文章 http://msdn.microsoft.com/en-us/library/fbk67b6z.aspx
UPDATE
除了将网格放到 Winform 上之外,我还需要在设计器中做任何事情吗?
using System;
using System.Data;
using System.Data.SqlClient;
using System.Data.SQLite;
using System.Windows.Forms;
namespace CC
{
public partial class Form1 : Form
{
private BindingSource bindingSource1 = new BindingSource();
private SQLiteDataAdapter dataAdapter = new SQLiteDataAdapter();
public Form1()
{
InitializeComponent();
dataGridView1 = new DataGridView();
this.Load += new System.EventHandler(Form1_Load);
this.Text = "Cars";
}
private void Form1_Load(object sender, EventArgs e)
{
dataGridView1.DataSource = bindingSource1;
GetData("select * from Cars");
}
private void GetData(string selectCommand)
{
string dbPath = "c:\\temp\\cars.db";
try
{
var connectionString = "Data Source=" + dbPath + ";Version=3";
dataAdapter = new SQLiteDataAdapter(selectCommand, connectionString);
SQLiteCommandBuilder commandBuilder = new SQLiteCommandBuilder(dataAdapter);
DataTable table = new DataTable();
table.Locale = System.Globalization.CultureInfo.InvariantCulture;
dataAdapter.Fill(table);
bindingSource1.DataSource = table;
// Resize the DataGridView columns to fit the newly loaded content.
dataGridView1.AutoResizeColumns(
DataGridViewAutoSizeColumnsMode.AllCellsExceptHeader);
}
catch (SqlException)
{
MessageBox.Show("To run this example, replace the value of the " +
"connectionString variable with a connection string that is " +
"valid for your system.");
}
}
}
}
我认为您需要指定 DataMember 属性。而且我认为您不需要绑定源对象,直接可以将 DataTable 绑定到 DataGridView 控件。
我附上一段代码,有助于将 gridview 控件与 SQL Server 数据库绑定,它对我来说效果很好。
using(SqlDataAdapter sqlDataAdapter =
new SqlDataAdapter("SELECT * FROM Table1",
"Server=.\\SQLEXPRESS; Integrated Security=SSPI; Database=SampleDb"))
{
using (DataTable dataTable = new DataTable())
{
sqlDataAdapter.Fill(dataTable);
this.dataGridView1.DataSource = dataTable;
}
}
抱歉,我没有安装 SQLite :(
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)