Reputation: 263
In the above images ,in console window i am having two hardware addresses and two ip addresses but datagrid is displaying only last result what would be the reason for this why datagrid is skipping one result?
Code is :
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 is:
<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>
Upvotes: 0
Views: 132
Reputation: 10460
Your problem is the following: the string you use contains this part in it somewhere:
...
Hardware Address : F8- ...
Hardware Address : F8- ...
IP Address : 192...
IP Address : 192...
...
When you are parsing the string (stringData
) you are only taking one match into consideration (the last one).
Fix it like this:
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();
}
Of course this code only works well if there are exactly the same number of matches for both patterns.
Upvotes: 1