目的:控制DataGridView按照自定义列显示数据
如果DataGridView不设定列,那么会自动按照数据源的表来创建列,但这样就无法控制具体某列的外观,为此需要自定义列
//1、用Visual C# 2005界面设计器 添加一个DataGridView,然后添加自定义列,设置列名
//2、创建数据表
DataTable table = new DataTable();
table.Columns.Add("附件", Type.GetType("System.String"));
table.Columns.Add("主题",Type.GetType("System.String"));
table.Columns.Add("发件人", Type.GetType("System.String"));
table.Columns.Add("单位", Type.GetType("System.String"));
table.Columns.Add("发件时间", Type.GetType("System.String"));
table.Columns.Add("链接",Type.GetType("System.String"));
//3、dataGridView和table的列名映射
dataGridView1.Columns["attachtment"].DataPropertyName = "附件";
dataGridView1.Columns["subject"].DataPropertyName = "主题";
dataGridView1.Columns["sender"].DataPropertyName = "发件人";
dataGridView1.Columns["department"].DataPropertyName = "单位";
dataGridView1.Columns["sendDatetime"].DataPropertyName = "发件时间";
dataGridView1.Columns["link"].DataPropertyName = "链接";
//4、使用数据填充table
//5、绑定table到dataGridView
dataGridView1.DataSource = table;
从dataGridView中获取被选中列的代码
foreach (DataGridViewRow row in this.dataGridView1.SelectedRows)
{
string data = row.Cells["link"].Value.ToString();
}