我正在使用C#WPF处理基于网络的应用程序。该应用程序的目的是通过在后端运行的telnet命令配置网络设备。
我遇到的问题是数据网格中显示的多个值是由用户添加的,现在我想迭代所有值并配置我的设备。我使用ObservableCollection
来保存数据网格中存在的值但是在foreach循环中我无法遍历所有值并填充它们,因为我认为问题是我的ObservableCollection
为空。请告诉我填写数据的方式。
这是我的代码:
public ObservableCollection<VLANSPropertyClass> vlan { get; set; }
public bool VLAN()
{
vlan = new ObservableCollection<VLANSPropertyClass>();
string _command;
_command = "config t \n";
WriteAPCommand(_command);
ReadAPCommand();
foreach(VLANSPropertyClass v in vlan)
{
Console.WriteLine("-----------------FOREACH STARTED----------------");
_command = "vlan " + v.vid + "\n";
WriteAPCommand(_command);
ReadAPCommand();
_command = "name " + v.vname + "\n";
WriteAPCommand(_command);
ReadAPCommand();
_command = "interface " + v.vid + "\n";
WriteAPCommand(_command);
ReadAPCommand();
_command = "ip address " + v.ip + " " + v.mask + "\n";
WriteAPCommand(_command);
ReadAPCommand();
_command="exit\r";
WriteAPCommand(_command);
ReadAPCommand();
_command = "interface " + v.vports + "\n";
WriteAPCommand(_command);
ReadAPCommand();
_command = "switchport access " + v.vid + "\n";
WriteAPCommand(_command);
ReadAPCommand();
_command = "copy runningconfig startupconfig\n";
WriteAPCommand(_command);
ReadAPCommand();
}
Console.WriteLine("-----------------FOREACH COMPLETED----------------");
return true;
}
VLANSProperty类是:
public class VLANSPropertyClass
{
public string vname { get; set; }
public int S_No { get; set; }
public string vid { get; set; }
public string ip { get; set; }
public string mask { get; set; }
public string vports { get; set; }
}
读写方法是:
public void WriteAPCommand(string _apCommand)
{
_telnetData = new byte[1024];
_telnetData = Encoding.ASCII.GetBytes(_apCommand);
_networkstream.Write(_telnetData, 0, _telnetData.Length);
Thread.Sleep(2000);
}
public string ReadAPCommand()
{
_telnetData = new byte[1024];
_recvBytes = _networkstream.Read(_telnetData, 0, _telnetData.Length);
_stringData = Encoding.ASCII.GetString(_telnetData, 0, _recvBytes);
Console.WriteLine(_stringData);
return _stringData;
}
答案 0 :(得分:0)
您需要先使用数据填充集合,然后才能对其进行迭代并对项目值执行任何操作。如何填充您的收藏以及如何获取数据完全取决于您。我们不了解这些细节,但总的来说,你会做这样的事情:
vlan = new ObservableCollection<VLANSPropertyClass>();
VLANSPropertyClass item = new VLANSPropertyClass("fill", "with", "valid", "values");
vlan.Add(item);
或者,如果您从外部来源访问数据:
foreach (VLANSPropertyClass item in SomeDataAccessMethodThatReturnsACollection)
{
vlan.Add(item);
}