C#:无法以编程方式填充 DataGridView

发布于 2024-10-28 23:02:10 字数 2278 浏览 1 评论 0原文

我没有使用设计器,而是尝试以编程方式填充我放在 Winform 上的 DataGridView。当我查看调试器下的表格时,它具有正确的列和行数。问题是网格在我的表单上显示为空的灰色框。当我通过 VS 2008 Designer 将网格绑定到数据库时,它工作得很好。我怎样才能找到问题所在?

更新

我几乎是从这篇MSDN文章< /a>

更新

除了将网格放到 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.");
            }
        }


    }
}

Rather than use the designer I'm trying to populate a DataGridView I've put on my Winform programmatically. When I look in the table under the debugger it has the correct columns and number of rows. The problem is the grid appears as an empty grey box on my form. When I bind the grid to the database via VS 2008 Designer it worked fine. How can I track down the problem?

UPDATE

I pretty much took this from this MSDN Article

UPDATE

Do I have to do anything in the designer other than drop the grid on the 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.");
            }
        }


    }
}

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

只涨不跌 2024-11-04 23:02:10

我认为您需要指定 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 :(

I think you need to specify the DataMember property. And I think you don't require binding source object, directly you can bind DataTable to DataGridView control.

I am attaching a code which helps to bind gridview control with SQL Server database, and it works fine for me.

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;
    }
}

Sorry I don't have SQLite installed :(

北恋 2024-11-04 23:02:10

基本上我认为你不应该让这个复杂化!这是一个简单的方法:

        string cs = @"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=your db location;"; //connection string
        string sql = "SELECT * FROM table_name"; //sql statment to display all data
        OleDbConnection conn = new OleDbConnection(cs); //connectiion
        OleDbDataAdapter da = new OleDbDataAdapter(sql, conn); //data adapter object
        DataSet ds = new DataSet(); //dataset object to keep data in table
        conn.Open(); //open connection
        da.Fill(ds, "table_name"); // fill the dataset with table_name through data adapter
        conn.Close(); //close connection
        dataGridView1.DataSource = ds; //populate the datagridview with dataset
        dataGridView1.DataMember = "table_name"; // populate datagridview with table_name

basically i dont think u should complicate this! here's an easy way:

        string cs = @"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=your db location;"; //connection string
        string sql = "SELECT * FROM table_name"; //sql statment to display all data
        OleDbConnection conn = new OleDbConnection(cs); //connectiion
        OleDbDataAdapter da = new OleDbDataAdapter(sql, conn); //data adapter object
        DataSet ds = new DataSet(); //dataset object to keep data in table
        conn.Open(); //open connection
        da.Fill(ds, "table_name"); // fill the dataset with table_name through data adapter
        conn.Close(); //close connection
        dataGridView1.DataSource = ds; //populate the datagridview with dataset
        dataGridView1.DataMember = "table_name"; // populate datagridview with table_name
可爱咩 2024-11-04 23:02:10

我在使用 sqlite 以及与 linq 绑定时遇到困难。现在我遇到了与上面相同的问题,最终循环数据表来填充网格。

在使用数据表和数据绑定时,我注意到 sqlite 存在其他小问题,所以我猜问题出在 sqlite 上。

这是一些可以为任何人节省时间的代码。

int rowcount = 0;
foreach (DataRow row in dataTable.Rows)  
{
    dataGrid.Rows.Add();
    int column = 0;
    foreach (var item in row.ItemArray)
    {
        dataGrid.Rows[rowcount].Cells[column].Value = item;
        column++;
    }
    rowcount++;
}

I have has difficulties with sqlite and also binding with linq. Now I have the same issue as above and ended up looping the data table to fill the grid.

I have noticed other minor issues with sqlite when using datatables and also databinding so I guess the problem lies with sqlite.

Here's some code to save time for anyone.

int rowcount = 0;
foreach (DataRow row in dataTable.Rows)  
{
    dataGrid.Rows.Add();
    int column = 0;
    foreach (var item in row.ItemArray)
    {
        dataGrid.Rows[rowcount].Cells[column].Value = item;
        column++;
    }
    rowcount++;
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文