我在c# WinForm上显示XML时遇到问题。
我的 XML 文件如下所示:
<HotelDatabase>
<Hotel Name="ABC" Location="XYZ">
<Room Type="Single" Count="5" Price="2000" />
<Room Type="Superior" Count="3" Price="4000" />
</Hotel>
<Hotel Name="DEF" Location="LMN">
<Room Type="Single" Count="5" Price="2000" />
<Room Type="Superior" Count="3" Price="4000" />
</Hotel>
</HotelDatabase>
用于在 DataGridView 中显示数据的代码如下所示:
var dataSet = new DataSet();
dataSet.ReadXml(Properties.Settings.Default.HotelDB);
dataGridViewHotelList.DataSource = dataSet.Tables[0];
当我运行此代码时,仅显示名称和位置。我希望 Hotel 元素及其子元素中的所有属性都显示在数据网格视图中。
您正在正确地将 XML 数据加载到网格,但您应该知道当您DataGridView
绑定到DataTable
时,它显示的是数据表的列而不是相关表的列。
您不能在单个DataGridView
中显示关系。若要显示酒店的子项,可以使用相同窗体的另一个DataGridView
来显示酒店的子项,并将第二个网格绑定到酒店的房间:
var ds = new DataSet();
ds.ReadXml("path to xml file");
dataGridView1.DataSource = ds.Tables["Hotel"]; //Tables[0]
dataGridView2.DataSource = ds.Tables["Hotel"]; //Tables[0]
dataGridView2.DataMember = "Hotel_Room"; //ds.Tables[0].ChildRelations[0].RelationName;
这样,数据网格之间将具有主从关系。通过单击每个酒店行,您将看到其房间。
您还有其他一些选择,例如:
- 您可以创建网格的
DataGridViewButtonColumn
,该网格将打开一个窗体,该窗体显示包含所选酒店客房的网格。 - 可以使用
DataGrid
控件,该控件可以显示指向行的子项的链接。为此,将酒店设置为数据网格控制的数据源就足够了:this.dataGrid1.DataSource = ds.Tables["Hotel"];
您可以将XML转换为数据表,只需使用DataTable.ReadXML()将其插入网格视图,以下是MSDN的示例代码:
private static void DemonstrateReadWriteXMLDocumentWithString()
{
DataTable table = CreateTestTable("XmlDemo");
PrintValues(table, "Original table");
string fileName = "C:\TestData.xml";
table.WriteXml(fileName, XmlWriteMode.WriteSchema);
DataTable newTable = new DataTable();
newTable.ReadXml(fileName);
// Print out values in the table.
PrintValues(newTable, "New table");
}
private static DataTable CreateTestTable(string tableName)
{
// Create a test DataTable with two columns and a few rows.
DataTable table = new DataTable(tableName);
DataColumn column = new DataColumn("id", typeof(System.Int32));
column.AutoIncrement = true;
table.Columns.Add(column);
column = new DataColumn("item", typeof(System.String));
table.Columns.Add(column);
// Add ten rows.
DataRow row;
for (int i = 0; i <= 9; i++)
{
row = table.NewRow();
row["item"] = "item " + i;
table.Rows.Add(row);
}
table.AcceptChanges();
return table;
}
private static void PrintValues(DataTable table, string label)
{
Console.WriteLine(label);
foreach (DataRow row in table.Rows)
{
foreach (DataColumn column in table.Columns)
{
Console.Write("t{0}", row[column]);
}
Console.WriteLine();
}
}
如果您需要知道如何将 datagridview 绑定到数据表,这里有一个有关如何执行此操作的链接。