开发者

Bind DataSet column types to DataGridViewColumns?

开发者 https://www.devze.com 2023-03-13 20:32 出处:网络
I have a set of data coming into a DataGridView from another DataGridView (described here, question solved).

I have a set of data coming into a DataGridView from another DataGridView (described here, question solved).

I now wish to add two new columns to my DataSet, one Integer, one Boolean, with the Integer column being of type DataGridViewNumericUpDownColumn (gratefully thieved from this MSDN page), and the Boolean column being of DataGridViewCheckBoxColumn type.

If I add the columns directly to the DataSet, I can't seem to specify the DataGridViewColumn type for the Integer column.

If I set the DataSet as the DataSource of the DataGridView, then add the columns to the DataGridView, then the columns exist, but aren't bound back to the DataSet, which does not contain those columns.

How do I开发者_StackOverflow中文版 get these two columns to bind to the DataGridViewColumns, with the correct column type?


To do this you need to set the AutoGenerateColumns property of the DataGridView to false and add the columns yourself to both the DataSet and the DataGridView. DataGridView columns have the DataPropertyName property which allows you to set up binding to the underlying DataSource.

What you can do is have the AutoGenerateColumns property set true, add the DataSet as the DataSource for the grid (thus getting most of your needed columns), then turn AutoGenerateColumns off and add the Integer and Boolean columns to the dataset and the grid.

Below is some example code, binding against a DataTable:

DataTable dataTable = new DataTable();

DataColumn col1 = new DataColumn("Id",typeof(int));
col1.AutoIncrement = true;

DataColumn col2 = new DataColumn("Name",typeof(string));    
DataColumn col3 = new DataColumn("TimeStamp",typeof(DateTime));

dataTable.Columns.AddRange(new DataColumn[] { col1, col2, col3 }); 

dataTable.Rows.Add(null,"John",DateTime.Now);    
dataTable.Rows.Add(null,"Jane",DateTime.Now);         

BindingSource source = new BindingSource();
source.DataSource = dataTable;
dataGridView1.DataSource = source;

dataGridView1.AutoGenerateColumns = false;

DataColumn col4 = new DataColumn("CheckCol", typeof(bool));
dataTable.Columns.Add(col4);

DataGridViewCheckBoxColumn dgvcol1 = new DataGridViewCheckBoxColumn();
dgvcol1.DataPropertyName = "CheckCol";
dgvcol1.Name = "Select";

dataGridView1.Columns.Add(dgvcol1);

I haven't implemented the NumericUpDown column type, but it should work just the same as the check box column type shown.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号