2014-04-16 51 views
0

enter image description herewpf datagrid未显示完整结果?

enter image description here

在上面的图片,在控制台窗口我有两个硬件地址和两个IP地址,但数据网格中只显示最后的结果会是什么造成这种情况的原因DataGrid中被跳过一个结果?

代码是:

C#:

public class IPMAC 
     { 
      public string ip { get; set; } 
      public string mac { get; set; } 



     } 

    public ObservableCollection<IPMAC> ipmac { get; set; } 


     public MainWindow() 
     { 
      InitializeComponent(); 
      ipmac = new ObservableCollection<IPMAC>(); 
      this.DataContext = this; 


     } 
    var item = new IPMAC(); 
       string pattern = @"(F8-F7-D3-00\S+)"; 
       MatchCollection matches = Regex.Matches(stringData, pattern); 





       foreach (Match match in matches) 
       { 
        Console.WriteLine("Hardware Address : {0}", match.Groups[1].Value); 
        // ipmac.Add(new IPMAC() { mac = match.Groups[1].Value }); 

        item.mac = match.Groups[1].Value; 

       } 
       // ipmac.Add(item); 

       string pattern2 = @"(192.168.1\S+)"; 
       MatchCollection matchesIP = Regex.Matches(stringData, pattern2); 
       foreach (Match match in matchesIP) 
       { 
        Console.WriteLine("IP Address : {0}", match.Groups[1].Value); 
        // ipmac.Add(new IPMAC() { ip = match.Groups[1].Value }); 

        item.ip = match.Groups[1].Value; 

       } 
       ipmac.Add(item); 

      } 
      private void DataGrid_Loaded(object sender, RoutedEventArgs e) 
      { 
       dg.ItemsSource = ipmac; 
      } 

XAML是:

<DataGrid 
        Name="dg" 
        Grid.Row="0" 
        Height="250" 
       ItemsSource="{Binding ipmac}" 
        AutoGenerateColumns="False"    

        IsReadOnly="True" 
      > 
      <DataGrid.Columns> 
       <DataGridTextColumn Header="Mac Addresses" Binding="{Binding Path=mac}" /> 
       <DataGridTextColumn Header="IP Addresses" Binding="{Binding Path=ip}"/> 


      </DataGrid.Columns> 
     </DataGrid> 
+1

您只将一个数据添加到列表 – Sajeetharan

+0

@Sajeetharan ..在哪里? – TheSpy

+0

我需要在列表中添加另一个数据? – TheSpy

回答

1

你的问题如下:您使用的字符串中包含这部分在它的地方:

... 
Hardware Address : F8- ... 
Hardware Address : F8- ... 
IP Address : 192... 
IP Address : 192... 
... 

Wh如果您正在解析字符串(stringData),则只考虑一个匹配项(最后一项)。

修复这样的:

  string pattern = @"(F8-F7-D3-00\S+)"; 
      Match match = Regex.Match(stringData, pattern); 

      string pattern2 = @"(192.168.1\S+)"; 
      Match matchIP = Regex.Match(stringData, pattern2); 

      while (match.Success && matchIp.Success) 
      { 
        var item = new IPMAC(); 
        item.mac = match.Value; 
        item.ip = matchIP.Value; 
        ipmac.Add(item); 

        match= match.NextMatch(); 
        matchIp = matchIp.NextMatch(); 
      } 

当然,如果恰好有两个模式相同数量的匹配这个代码仅效果很好。

+0

@ qqbenq..great它工作:) ..谢谢 – TheSpy