【问题标题】:C#: Can't populate DataGridView programmaticallyC#:无法以编程方式填充 DataGridView
【发布时间】:2011-03-30 12:45:50
【问题描述】:

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

更新

我几乎从 MSDN Article 那里得到了这个

更新

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


    }
}

【问题讨论】:

    标签: c# winforms sqlite datagridview


    【解决方案1】:

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

    【讨论】:

    • @vs dev:我尝试将 DataMember 设置为“汽车”,但这并没有解决问题。
    • 奇怪,我在源代码中找不到任何问题,而不是使用BindingSource类,您是否尝试使用Simple DataTable?
    • @vs dev 对不起,我是新手;您能否在答案中添加我需要更改/添加的代码示例?
    • 我在设计器中添加了 GridView。
    • @vs_dev - 谢谢。我更改了您的 sqlite 代码,将其添加到 Form1_Load 并且一切正常。
    【解决方案2】:

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

            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
    

    【讨论】:

      【解决方案3】:

      我在使用 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++;
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-05-04
        • 1970-01-01
        • 2020-10-15
        • 2013-09-13
        • 1970-01-01
        • 2015-12-13
        相关资源
        最近更新 更多