问题绑定DataTable到DataGridView -我错过了一个步骤

本文关键字:一个 错过了 DataTable 绑定 DataGridView 问题 | 更新日期: 2023-09-27 18:15:11

在我的Windows窗体应用程序中,我有一个DataGridView,它将通过代码后面的数据表以编程方式绑定。我已经这样做了好几个星期了,但这是因为我没有在DGV设计器中手动指定列和列类型-所以在绑定表时自动创建列。

一旦我手动给出列和列名,并将DGV的AutoGenerateColumns属性设置为false,那么在绑定后DGV中总是只有1行,并且所有值都为空-因此似乎从我的DataTable的值似乎没有映射到DGV。我已经确保DGV中的列的名称与DataTable中的列的名称匹配。

任何想法?这里有一些代码(目前不能复制粘贴任何代码,所以这里是我所拥有的一个粗略的想法):

DataTable dt = new DataTable();
dt.Columns.Add("ID",typeof(long));
//etc...
var linqQuery = //perform linq query to get data
foreach (var data in linqQuery)
{
   dt.Rows.Add(data.ID,//etc);
}
dgv.DataSource = dt;

问题绑定DataTable到DataGridView -我错过了一个步骤

这是我的愚蠢之举。我没有设置DataPropertyName。分析。谢谢!

由于您启用了autogeneratecolcolumns,您需要将您的DGV中的每个列的DataPropertyName设置为数据源中匹配的列名

你可以这样尝试。用于将数据网格视图列映射到数据表..

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
namespace TestWinApp
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }    
        private void Form1_Load(object sender, EventArgs e)
        {
            DataSet dsPlayerList = new DataSet();
            DataTable dt = new DataTable("PlayerList");
            dsPlayerList.Tables.Add(dt);
            dt.Columns.Add("ID",typeof(int));
            dt.Columns.Add("Name",typeof(string));
            dt.Columns.Add("Type", typeof(string));
            dt.Columns.Add("IP", typeof(string));
            DataRow dr = dt.NewRow();
            dr["ID"] = 1;
            dr["Name"] = "Player 1";
            dr["Type"] = "Standard";
            dr["IP"] = "127.0.0.1";
            dt.Rows.Add(dr);
            dr = dt.NewRow();
            dr["ID"] = 2;
            dr["Name"] = "Player 2";
            dr["Type"] = "Standard";
            dr["IP"] = "127.0.0.1";
            dt.Rows.Add(dr);
            dt.AcceptChanges();
            this.dgvPlayerList.AutoGenerateColumns = false;    
            DataGridViewTextBoxColumn col = new DataGridViewTextBoxColumn();
            col.DataPropertyName = "Name";
            col.Name = "Name";
            col.HeaderText = "Name";                
            this.dgvPlayerList.Columns.Add(col);
            col = new DataGridViewTextBoxColumn();
            col.DataPropertyName = "Type";
            col.Name = "Type";
            col.HeaderText = "Type";    
            this.dgvPlayerList.Columns.Add(col);
            this.dgvPlayerList.DataSource = dsPlayerList.Tables["PlayerList"];            
        }        
    }
}