以前做WinForm接触的不多字典类型而且返回在List<T>中,在dataGridView绑定的时候遇到问题,单元格显示集合并不显示数据,在窗体上放一个dataGridView,
下面是类:
public class Certification
{
Dictionary<String, String> Descrribed;
public Dictionary<String, String> Descrribed1
{
get { return Descrribed; }
set { Descrribed = value; }
}
String CertificationStatus;
public String CertificationStatus1
{
get { return CertificationStatus; }
set { CertificationStatus = value; }
}
public Certification(Dictionary<String, String> _dic, String _status)
{
this.Descrribed1 = _dic;
this.CertificationStatus1 = _status;
}
}
在窗体Load事件中加上
动态创建列名:
DataGridViewTextBoxColumn txtKey = new DataGridViewTextBoxColumn();
txtKey.Name = "txtKey";
txtKey.HeaderText = "txtKey";
this.dataGridView2.Columns.Add(txtKey);
DataGridViewTextBoxColumn txtValue = new DataGridViewTextBoxColumn();
txtValue.Name = "txtValue";
txtValue.HeaderText = "txtValue";
this.dataGridView2.Columns.Add(txtValue);
DataGridViewTextBoxColumn txtStatus = new DataGridViewTextBoxColumn();
txtStatus.Name = "txtStatus";
txtStatus.HeaderText = "txtStatus";
this.dataGridView2.Columns.Add(txtStatus);
泛型:
List<Certification> l_Test = new List<Certification>();
Certification cer = new Certification();
cer.Descrribed1 = new Dictionary<String, String>();
cer.Descrribed1.Add("123", "aaa");
cer.Descrribed1.Add("456", "bbb");
cer.Descrribed1.Add("789", "ccc");
cer.CertificationStatus1 = "离开";
cer.CertificationStatus1 = "在线";
cer.CertificationStatus1 = "忙碌";
l_Test.Add(cer);
绑定数据:
this.dataGridView2.Columns["txtKey"].DataPropertyName = "Descrribed1";
this.dataGridView2.Columns["txtStatus"].DataPropertyName = "CertificationStatus1";
this.dataGridView2.DataSource = l_Test;
显示效果:
不能显示dictionary的Key和Value
最后用循环处理,但是数据量大不好处理:
泛型添加数据:
Dictionary<String, String> dicDescribe = new Dictionary<String, String>();
dicDescribe.Add("标题", "描述");
Dictionary<String, String> dicName = new Dictionary<String, String>();
dicName.Add("名称", "内容");
l_Test.Add(new Certification(dicDescribe, "离开"));
l_Test.Add(new Certification(dicName, "忙碌"));
l_Test.Add(new Certification(null, "在线"));
循环写入数据:
String sKey = String.Empty;
String sValue = String.Empty;
int nRow = 0;
foreach (Certification l_cer in l_Test)
{
//添加行
DataGridViewRow dbRow = new DataGridViewRow();
this.dataGridView2.Rows.Add(dbRow);
String sStatus = l_cer.CertificationStatus1.ToString();
if (l_cer.Descrribed1 != null)
{
foreach (KeyValuePair<String, String> item in l_cer.Descrribed1)
{
sKey = item.Key.ToString();
sValue = item.Value.ToString();
}
}
else
{
sKey = "";
sValue = "";
}
this.dataGridView2.Rows[nRow].Cells[0].Value = sKey;
this.dataGridView2.Rows[nRow].Cells[1].Value = sValue;
this.dataGridView2.Rows[nRow].Cells[2].Value = sStatus;
nRow++;
}
显示:
各位老大谁有更好的办法处理?