C# datagridview 赋值方式

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#)