[英]How to create and attach rows to this DataGridView?
I'm beginner in .Net ,so maybe my question will seem naive to some of you. 我是.Net的初学者,所以也许我的问题对某些人似乎很幼稚。
I have DataGridView table in WinForm project: 我在WinForm项目中有DataGridView表:
It contain three columns(image,combobox and textBox columns). 它包含三列(图像,组合框和文本框列)。
Any idea how to create and attach rows to this table? 任何想法如何创建表并将行附加到该表?
Thank you in advance! 先感谢您!
You create a data source, then bind the data source to the grid's DataSource property. 您创建一个数据源,然后将数据源绑定到网格的DataSource属性。 You then add a record to your data source. 然后,您将一条记录添加到您的数据源。
// create data source
BindingList<Shape> dataSource = new BindingList<Shape>();
// add record to data source
dataSource.Add(new Shape("Some Contour", "Circle", "Some Name"));
// bind data source
yourDataGridView.DataSource = typeof(BindingList<Shape>);
yourDataGridView.DataSource = dataSource;
Set the DataPropertyName of each column to matches the names of the fields in your Shape class. 将每列的DataPropertyName设置为与Shape类中的字段名称匹配。
DataGridViewTextBoxColumn colName = new DataGridViewTextBoxColumn();
colName.DataPropertyName = "Name";
yourDataGridView.Columns.Add(colName );
However, I recommend you use Virtual Mode instead to keep your data separate and decoupled. 但是,我建议您改用虚拟模式来保持数据分离和分离。
If you wish to accept inputs from user, you have to create a form on this page using which the user can provide inputs. 如果您希望接受用户的输入,则必须在此页面上创建一个表单,用户可以使用该表单来提供输入。 Take those values and add them to a DataTable. 取这些值并将它们添加到DataTable中。 Following is a sample snippet showing it: 以下是显示它的样本片段:
DataTable dt = new DataTable();
dt.Columns.Add("Contour",typeof(string)); //I am assuming that you will store path
//of image in the DataTable
dt.Columns.Add("Shape",typeof(string));
dt.Columns.Add("Name",typeof(string));
Keep adding new rows to the DataTable as you receive inputs from the user: 在收到用户的输入时,请继续向DataTable添加新行:
DataRow row = dt.NewRow();
row["Contour"] = txtContourPath.Text;
row["Shape"] = ddlShape.SelectedValue;
row["Name"] = txtName.Text;
dt.Rows.Add(row);
Assign above DataTable to DataSource property of the GridView. 将上面的DataTable分配给GridView的DataSource属性。
dgv.DataSource = dt;
You can use method: 您可以使用方法:
Hope I can help you. 希望我能为您服务。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.