1.DataGridView中一列一列的绑定(列名存在集合arrList中,数据存在DataTable)
解释:集合(arrList)中存SQL语句SELECT中的”名字”转换成DataTable的“列名”
//通过集合中的名字创建列名
protected DataTable CreateTable(ArrayList arrList, DataReader reader)
// reader可以从ExecuteReader获得
{
// DataTable的名字
DataTable dt = new DataTable("table");
//给DataTable定列名
for (int i = 0; i < arrList.Count; i++)
{
DataColumn dtColumn = new DataColumn();
dtColumn.ColumnName = (string)arrList[i];
dt.Columns.Add(dtColumn);
}
//往DataTable里加行
DataRow dtRow;
while (reader.Read())
{
dtRow = dt.NewRow();
for (int i = 0; i < arrList.Count; i++)
{
try
{
dtRow[(string)arrList[i]] = reader.GetValue(i).ToString();
}
catch
{
dtRow[(string)arrList[i]] = System.DBNull.Value;
}
}
dt.Rows.Add(dtRow);
}
return dt;
}
//将DataTable绑定到DataView中
DataView dvListViewInfo = new DataView(m_listViewInfo);
dataGridView1.Columns.Clear();
//取消dataGridView1按默认方式显示
dataGridView1.AutoGenerateColumns = false;
//绑定DataView到dataGridView上
dataGridView1.DataSource = dvListViewInfo;
DataGridViewTextBoxColumn dtcTimeStamp = new DataGridViewTextBoxColumn();
dtcTimeStamp.DataPropertyName = "TIMESTAMP";//SQL语句得到的列名,可从集合中获得
dtcTimeStamp.HeaderText = "日期";//列头显示的汉字
dtcTimeStamp.Width = 110;
dataGridView1.Columns.Add(dtcTimeStamp);//最后一定要添加进去