我在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元素及其子元素中的所有属性都显示在datagridview中。
答案 0 :(得分:3)
您正在正确地将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"];
答案 1 :(得分:0)
您可以将XML转换为数据表,然后使用DataTable.ReadXML()将其插入到gridview中,这里是来自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绑定到数据表here,那么就是如何做到这一点的链接。