您的位置:首页 - 教程 - WinForm - 正文
DataGridView绑定List集合例子
思路是建立一个模型类,然后使用List泛型循环添加模型元素,然后指定DataGridView的DataSource为List集合的实例。

本文末尾附源码下载。

参考:http://hovertree.com/h/bjaf/feao233c.htm

效果图:



模型类:

using System;

namespace HoverTree.HtModel
{
/// <summary>
/// Url信息类
/// by 何问起
/// </summary>
public class UrlInfo
{
int _htId;
/// <summary>
/// ID
/// </summary>
public int HtId
{
get { return _htId; }
set { _htId = value; }
}

public string HtUrl
{
get
{
return _htUrl;
}

set
{
_htUrl = value;
}
}

public string HtSummary
{
get
{
return _htSummary;
}

set
{
_htSummary = value;
}
}

public DateTime HtAddTime
{
get
{
return _htAddTime;
}

set
{
_htAddTime = value;
}
}

public string HtTitle
{
get
{
return _htTitle;
}

set
{
_htTitle = value;
}
}

public bool HtULCase
{
get
{
return _htULCase;
}

set
{
_htULCase = value;
}
}

string _htUrl;
string _htSummary;
DateTime _htAddTime;
string _htTitle;
bool _htULCase = false;
}
}

建立Windows Forms :Form_hoverTree
代码如下:

using HoverTree.HtModel;
using System;
using System.Collections.Generic;
using System.Windows.Forms;

namespace HoverTreeDGV
{
public partial class Form_hoverTree : Form
{
public Form_hoverTree()
{
InitializeComponent();
}

private void Form_hoverTree_Load(object sender, EventArgs e)
{
List<UrlInfo> h_list = GetList();

dataGridView_hewenqi.DataSource = h_list;
}

private static List<UrlInfo> GetList()
{
List<UrlInfo> h_list = new List<UrlInfo>();

UrlInfo h_info = new UrlInfo();
h_info.HtAddTime = DateTime.Now;
h_info.HtId = 1;
h_info.HtSummary = "摘要1";
h_info.HtTitle = "何问起";
h_info.HtULCase = false;
h_info.HtUrl = "http://hovertree.com/";
h_list.Add(h_info);

h_info = new UrlInfo();
h_info.HtAddTime = DateTime.Now;
h_info.HtId = 2;
h_info.HtSummary = "摘要2";
h_info.HtTitle = "快速封装";
h_info.HtULCase = true;
h_info.HtUrl = "http://hovertree.com/h/bjaf/fengzhuangziduan.htm";
h_list.Add(h_info);

h_info = new UrlInfo();
h_info.HtAddTime = DateTime.Now;
h_info.HtId = 3;
h_info.HtSummary = "摘要3";
h_info.HtTitle = "base64编码";
h_info.HtULCase = true;
h_info.HtUrl = "http://hovertree.com/h/bjaf/wa5nbd3w.htm";
h_list.Add(h_info);

h_info = new UrlInfo();
h_info.HtAddTime = DateTime.Now;
h_info.HtId = 4;
h_info.HtSummary = "柯乐义首页";
h_info.HtTitle = "柯乐义";
h_info.HtULCase = false;
h_info.HtUrl = "http://keleyi.com/";
h_list.Add(h_info);
return h_list;
}

private void linkLabel_hovertree_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
{ System.Diagnostics.Process.Start("http://hovertree.com/h/bjaf/1x1yn77e.htm");
}
}
}
源码下载:http://hovertree.com/h/bjaf/bbot18bj.htm

关于DataGridView的文章:
datagridview修改列名(显示的名称)

DataGridView绑定List集合例子

评论: