问题
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