Binding GridView to dynamic DataTable

安稳与你 提交于 2019-12-13 06:16:17

问题


I have a GridView and I am binding it to a DataTable which is being filled at run time. Number of columns and rows are not fixed. After the DataTable is filled I am setting the binding source of the GridView to this data table:

 Me.User_infoDTBindingSource.DataSource = User_infoDT

Now the prblem is, gird view is not showing any columns or rows at all. I used :

Me.UserListGridView.PopulateColumns(User_infoDT)

Now I am getting all the columns in the GridView but the column captions which I setted in DataTable are all lost. The rows ar still empty in the GridView. I have also used OptionView.EnableAppearanceEvenRow so I can see that number of rows are generating in my GridView (as it is supposed to be) but still I can't see any data.

I have implemented the same code with Windows DataGridView and TreeList using the same data source (data table) and it is working perfectly. But here I can not find any reason of not getting the rows.

Any idea where are these rows? I debugged the code and checked the DataTable when I am setting the binding source's data source to data table. At that time GridView.DataRowCount and GridView.Columns.Count are correct. But still grid view is not showing any data in the rows.

UPDATE: I have now removed the binding source and setted the GridView's datasource directly to the DataTable and it is working perfectly!! I am amazed why the rows are invisble when I am using a binding source in between. Apart from this, here now all the columns have correct captions also (which I setted in DataTable) which are being lost when I am using binding source.


回答1:


Try this

using System;
using System.Data;
using System.Windows.Forms;

namespace WindowsFormsApplication1
{
  public partial class Form1 : Form
  {
    DataTable table = new DataTable();
    BindingSource bind = new BindingSource();

    public Form1()
    {
      InitializeComponent();
      table.Columns.Add(new DataColumn("Name", typeof(string)));
      table.Columns.Add(new DataColumn("Value", typeof(Int32)));
      bind.DataSource = table;
      dataGridView1.DataSource = bind;
    }

    private void button1_Click(object sender, EventArgs e)
    {
      table.Columns.Add(new DataColumn("Check", typeof(bool)));
    }
  }
}



回答2:


Well I got the answer. I added following lines:

Me.UserListGridView.Columns.Clear()
Me.UserListGridView.OptionsBehavior.AutoPopulateColumns = True
Me.User_infoDTBindingSource.DataSource = _user_info.User_infoDT
Me.User_infoDTBindingSource.RaiseListChangedEvents = True
Me.User_infoDTBindingSource.ResetBindings(True)

After setting the datasource, raising the list changed events and resetting binding resolved the issue.



来源:https://stackoverflow.com/questions/26583727/binding-gridview-to-dynamic-datatable

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!