日期:2014-05-17  浏览次数:20923 次

DataGridView绑定DataTable中列的问题
已经指定了 DataGridView中列集合的列名 如:AAA,BBB,CCC 

现在有个DataTable ,列名:A1,B1,C1 分别对应 DataGridView中列AAA,BBB,CCC 

请问怎么把DataTable数据 正确的绑定在DataGridView中?




------解决方案--------------------
dataGridView1.Columns["AAA"].DataPropertyName = "A1";
------解决方案--------------------
其中:DataPropertyName 对应你要绑定的DataTable的列名。
C# code

this.GV_ColumnInfo.AutoGenerateColumns = false;
this.GV_ColumnInfo.DataSource =你要绑定的dt;

                DataGridViewColumn fieldNameColumn = new DataGridViewTextBoxColumn();
                fieldNameColumn.HeaderText = "field_name";
                fieldNameColumn.DataPropertyName = "field-name";
                this.GV_ColumnInfo.Columns.Add(fieldNameColumn);

                DataGridViewColumn idColumn = new DataGridViewTextBoxColumn();
                idColumn.HeaderText = "id";
                idColumn.DataPropertyName = "id";
                this.GV_ColumnInfo.Columns.Add(idColumn);

                DataGridViewColumn identifierColumn = new DataGridViewTextBoxColumn();
                identifierColumn.HeaderText = "identifier";
                identifierColumn.DataPropertyName = "identifier";
                this.GV_ColumnInfo.Columns.Add(identifierColumn);

                //下拉列表绑定时候,DataPropertyName和ValueMember做对比,
                DataGridViewComboBoxColumn typeColumn = new DataGridViewComboBoxColumn();
                typeColumn.DataSource = GetComBoxDataSource();
                typeColumn.Width = 200;
                typeColumn.DataPropertyName = "type";
                typeColumn.DisplayMember = "Text";
                typeColumn.ValueMember = "Values";
                typeColumn.HeaderText = "type";
                //typeColumn = ComboBoxStyle.DropDownList;
                this.GV_ColumnInfo.Columns.Add(typeColumn);

                DataGridViewColumn lengthColumn = new DataGridViewTextBoxColumn();
                lengthColumn.HeaderText = "length";
                lengthColumn.DataPropertyName = "length";
                this.GV_ColumnInfo.Columns.Add(lengthColumn);