DataGridView是用于Windows Froms 2.0的新网格控件。它可以取代先前版本中DataGrid控件,它易于使用并高度可定制,支持很多我们的用户需要的特性。
在过滤显示数据库列表列表上有其不可代替的优势,同时对于实时显示对象多个属性上也很方便。
在datagridview上显示二维数组的demo,矩阵可以转化为数据显示,数据库中的数据基本上可通过其显示。
在winform中添加datagridview控件 ,在窗体加载中添加以下代码。
//2行5列的数组
int[,] TABLE = new int[,] { { 1, 2, 3 ,4,5}, { 4, 5, 6 ,7,8} };
//新建datatable用于储存数组
DataTable dt = new DataTable();
//获取数据列数
int ArrayColumnlength = TABLE.GetLength(1);
//获取数组行数
int ArrayRowlength = TABLE.GetLength(0);
//在datagridview中添加对应的列数
for (int i = 0; i < TABLE.GetLength(1); i++)
{
dt.Columns.Add(i.ToString(), typeof(int));
}
for (int i = 0; i < TABLE.GetLength(0); i++)
{
DataRow dr = dt.NewRow(); //遍历新建Row
for (int j = 0; j < TABLE.GetLength(1); j++)
{
dr[j] = TABLE[i, j];
}
//将Row元素赋值
dt.Rows.Add(dr);
}
this.dataGridView1.DataSource = dt;
for (int k = 0; k< TABLE.GetLength(0);k++ )
{
string temp1 = "第" + (k+1).ToString() + "行";
dataGridView1.Rows[k].HeaderCell.Value = temp1;
}
for (int h = 0; h < TABLE.GetLength(1); h++)
{
string temp2= "第" + (h + 1).ToString() + "列";
dataGridView1.Columns[h].HeaderCell.Value = temp2;
}