2016-12-25 71 views
0

我有一个WinForms应用程序,并希望绑定一个XML文件到DataGridView。在DataGridView的前两行中,我需要附加一个时间范围(HH:MM)时间格式。我如何实现这一点,以便所有的行都是可编辑的?在DataGridView中显示数据的最佳方式是什么?Winforms c#应用程序datagridview绑定

DataColumn col1 = new DataColumn("value", typeof(string)); 
DataColumn col2 = new DataColumn("comment", typeof(string)); 
this.table.Columns.Add(col1); 
this.table.Columns.Add(col2); 
this.table.ReadXml(AppDomain.CurrentDomain.BaseDirectory + "CFResource.xml"); 
table.Rows[0].Field<TimeSpan>("BhrFromTime").ToString(@"hh\:mm"); 
this.dataGridView1.DataSource = this.table; 

我的XML文件,如下所示:

<root> 
    <Time> 
    <data name="BhrFromTime" xml:space="preserve"> 
    <value>08:00</value> 
    <comment>Bhr start time</comment> 
    </data> 
    <data name="BhrToTime" xml:space="preserve"> 
    <value>19:00</value> 
    <comment>bhr from time</comment> 
    </data> 
    </Time> 
    <UserWarning> 
    <data name="U0001" xml:space="preserve"> 
    <value>UW1</value> 
    <comment>UserWarning 1</comment> 
    </data> 
    <data name="U0003" xml:space="preserve"> 
    <value>UW2</value> 
    <comment>UserWarning 3</comment> 
    </data> 
    <data name="U0002" xml:space="preserve"> 
    <value>UW3</value> 
    <comment>UserWarning 2</comment> 
    </data> 
    <data name="U0004" xml:space="preserve"> 
    <value>UW4</value> 
    <comment>UserWarning 4</comment> 
    </data> 
    <data name="U0007" xml:space="preserve"> 
    <value>UW5</value> 
    <comment>user warning 5</comment> 
    </data> 
    </UserWarning> 
</root> 

回答

2

也许最简单的方法是将XML文件加载到DataSet和你的情况绑定表data到DataGridView:

DataSet ds = new DataSet(); 
ds.ReadXml("xmlfile1.xml"); 
dataGridView1.DataSource = ds.Tables["data"]; 

哪产生这个:

enter image description here

相关问题