[英]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.