[英]Trying to create DataGridView from key-value pairs in C#
在Windows Form应用程序中,我试图创建一个包含两列的DataGridView:一列用于XML元素给出的键,另一列用于表示XML元素的值。 到目前为止这是我的代码:
this.myData = new DataGridView();
((System.ComponentModel.ISupportInitialize)(myData)).BeginInit();
myData.Location = new System.Drawing.Point(12, 42);
myData.Name = "myData";
myData.Size = new System.Drawing.Size(1060, 585);
myData.TabIndex = 32;
foreach (XElement xElem in xInfoItems)
{
numItems++;
}
myData.Columns.Add(new DataGridViewTextBoxColumn());
myData.Columns.Add(new DataGridViewTextBoxColumn());
myData.Columns[0].Name = "Key";
myData.Columns[0].DataPropertyName = "key";
myData.Columns[1].Name = "Value";
myData.Columns[1].DataPropertyName = "value";
List<myRow> data = new List<myRow>();
foreach (XElement xElem in xInfoItems)
{
data.Add(new myRow(xElem.Attribute("key").Value, xElem.Value));
}
myData.DataSource = data;
myData.Refresh();
this.PerformLayout();
我已经证实,所有的信息data
被通过的foreach加载,使部分工作。 我的问题是网格显示,但是网格上什么也没有显示。 我究竟做错了什么? 我对这种数据类型不太满意,因此我很抱歉这很明显。
我发现我没有在“设计”视图中正确设置myData。 添加myRow类后,它可以完美运行。 谢谢您的帮助!
问题可能出在您的myRow类中。 当我尝试重现您的代码时,我首先将“ key”和“ value”定义为myRow类的公共字段,如下所示:
public class myRow {
public string key;
public string value;
public myRow( string Key, string Value )
{
key = Key;
value = Value;
}
}
这导致显示绑定的行,但文本不在单元格中。 当我将它们都更改为属性时,绑定的效果更好:
public class myRow{
private string _key;
public string key
{
get
{
return _key;
}
}
private string _value;
public string value
{
get
{
return _value;
}
}
public myRow( string Key, string Value )
{
_key = Key;
_value = Value;
}
}
我对您的代码所做的修改可能会有所帮助。 (我只是专注于使用DataTable创建列并添加行的部分)。
this.myData = new DataGridView();
((System.ComponentModel.ISupportInitialize)(myData)).BeginInit();
myData.Location = new System.Drawing.Point(12, 42);
myData.Name = "myData";
myData.Size = new System.Drawing.Size(1060, 585);
myData.TabIndex = 32;
foreach (XElement xElem in xInfoItems)
{
numItems++;
}
// Here we create a DataTable with two columns.
DataTable table = new DataTable();
table.Columns.Add("Key", typeof(string));
table.Columns.Add("Value", typeof(string));
foreach (XElement xElem in xInfoItems)
{
//Here we add rows to table
table.Rows.Add(xElem.Attribute("key").Value, xElem.Value);
}
myData.DataSource = table;
myData.Refresh();
this.PerformLayout();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.