DataGridView dgv = new System.Windows.Forms.DataGridView();
//DataGridView未设置列名信息的时候可以直接指定DataSource
DataTable dt = new DataTable();
dt.Columns.Add("姓名", Type.GetType("System.String"));
dt.Columns.Add("性别", Type.GetType("System.String"));
dt.Columns.Add("年龄", Type.GetType("System.int16"));
dt.Rows.Add(new object[]{"路人甲","男",22});
dt.Rows.Add(new object[]{"路人乙","女",20});
dgv.DataSource = dt;
//DataGridView已经在可视化界面设置好列名后不能再指定DataSource(指定了显示会走样)
string[] names = {"路人甲","路人乙"};
string[] sexs = {"男","女"};
int [] ages = {22,20}
for (int i = 0; i < names.length; i++)
{
dgv.Rows.Add();
dgv.Rows[i].Cells[0].Value = names[i];
dgv.Rows[i].Cells[1].Value = sexs[i];
dgv.Rows[i].Cells[2].Value = ages[i];
}
本文介绍了如何使用C#中的DataGridView控件进行数据绑定。通过创建DataTable并设置列类型及数据,然后将其作为DataGridView的数据源来展示表格数据。此外,还提供了另一种方法,在DataGridView已设置列名的情况下逐行添加数据。
1万+

被折叠的 条评论
为什么被折叠?



