WinForm中手动绑定DataGridView的方法
1、先设定DataGridView显示的字段及样式
/// <summary>
/// Add column to DataGridView
/// </summary>
private void DataGridViewSet()
{
DataGridViewTextBoxColumn column = new DataGridViewTextBoxColumn();
column.ReadOnly = true;
// alarm ID column
column.HeaderText =Properties.Resources.SearchLocalLogFileDGVHeaderID;
column.DisplayIndex = 0;
column.Name = "colIdx";
DataGridView1.Columns.Add(column);
// level column
column = new DataGridViewTextBoxColumn();
column.HeaderText = Properties.Resources.SearchLocalLogFileDGVHeaderLevel;
column.DisplayIndex = 1;
column.Name = "colTypeId";
DataGridView1.Columns.Add(column);
// level description column
column = new DataGridViewTextBoxColumn();
column.HeaderText = Properties.Resources.SearchLocalLogFileDGVHeaderLevelDes;
column.DisplayIndex = 2;
column.Name = "colLevelDesc";
DataGridView1.Columns.Add(column);
// level image column
DataGridViewImageColumn imgColumn = new DataGridViewImageColumn();
imgColumn.ReadOnly = true;
imgColumn.HeaderText = Properties.Resources.SearchLocalLogFileDGVHeaderLevelImg;
imgColumn.DisplayIndex = 3;
imgColumn.Name = "colLevelSymbol";
DataGridView1.Columns.Add(imgColumn);
// occur time column
column = new DataGridViewTextBoxColumn();
column.HeaderText = Properties.Resources.SearchLocalLogFileDGVHeaderOccurTime;
column.DisplayIndex = 4;
column.Name = "colOccurAt";
column.Width = column.Width + 20;
DataGridView1.Columns.Add(column);
// user column
column = new DataGridViewTextBoxColumn();
column.HeaderText = Properties.Resources.SearchLocalLogFileDGVHeaderUserName;
column.DisplayIndex = 5;
column.Name = "colUserName";
DataGridView1.Columns.Add(column);
// message column
column = new DataGridViewTextBoxColumn();
column.HeaderText =Properties.Resources.SearchLocalLogFileDGVHeaderMessage;
column.DisplayIndex = 6;
column.Name = "colMessage";
DataGridView1.Columns.Add(column);
}
2、为DataGridView增加显示的数据
private void AddToDGV(List<string> entities)
{
for (int i = 0; i < entities.Count; i++)
{
DataGridViewRow dgvr = new DataGridViewRow();
DataGridViewTextBoxCell cell = new DataGridViewTextBoxCell();
cell.Value = DataGridView1.RowCount + 1;
dgvr.Cells.Add(cell);
cell = new DataGridViewTextBoxCell();
cell.Value = entities[i].Level;
dgvr.Cells.Add(cell);
cell = new DataGridViewTextBoxCell();
DataGridViewImageCell img = new DataGridViewImageCell();
cell.Value = "user do sth.";
img.Value = "";//picture's path.
dgvr.Cells.AddRange(cell, img);
cell = new DataGridViewTextBoxCell();
cell.Value = entities[i].OccurTime;
dgvr.Cells.Add(cell);
cell = new DataGridViewTextBoxCell();
cell.Value = entities[i].UserName;
if (string.IsNullOrEmpty(entities[i]))
{
cell.Value = "test";
}
dgvr.Cells.Add(cell);
cell = new DataGridViewTextBoxCell();
cell.Value = entities[i].MessageContent;
dgvr.Cells.Add(cell);
DataGridView1.Rows.Add(dgvr);
}
}
引自:http://www.cnblogs.com/love_study/archive/2010/11/25/1887715.html