我有一个有三列的gridview。网站名称,URL,状态。我从xml文件中获取网站名称和URL。获取url frm xml文件后,我想ping网站。如果ping成功,则gridview中的状态列将为绿色。如果ping失败,则状态列将为红色。
以下是我的代码。
foreach (XmlNode node in nodeList)
{
string Instance = node.Attributes["name"].Value.Trim();
foreach (XmlNode nodeChild in node.ChildNodes)
{
DataRow dr = dtIPCheckList.NewRow();
dr["Instance"] = Instance;
dr["WebServer"] = nodeChild.Attributes["name"].Value.Trim();
dr["URL"] = nodeChild.Attributes["IPFQDN"].Value.Trim();
dr["Status"] = "GREEN"; //hardcoding at the moment.
dtIPCheckList.Rows.Add(dr);
}
}
现在我正在对状态进行硬编码,但我希望ping并根据成功或失败显示状态。
请指导我。
答案 0 :(得分:2)
我刚写了这个简单的程序,它似乎有效:
namespace WebsitePingTest
{
using System;
using System.Data;
using System.Drawing;
using System.Net.NetworkInformation;
using System.Windows.Forms;
public partial class Form1 : Form
{
public Form1()
{
this.InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
var dt = new DataTable();
dt.Columns.Add(new DataColumn("Websitename", typeof(string)));
dt.Columns.Add(new DataColumn("URL", typeof(string)));
dt.Columns.Add(new DataColumn("Status", typeof(string)));
var row = dt.NewRow();
row["Websitename"] = "Google";
row["URL"] = "www.google.com";
dt.Rows.Add(row);
row = dt.NewRow();
row["Websitename"] = "Yahoo";
row["URL"] = "www.yahoo.com";
dt.Rows.Add(row);
row = dt.NewRow();
row["Websitename"] = "xasfjhasfkjh";
row["URL"] = "www.xasfjhasfkjh.com";
dt.Rows.Add(row);
var view = new DataView(dt);
this.dataGridView1.DataSource = view;
foreach (DataGridViewRow dataGridViewRow in dataGridView1.Rows)
{
var url = dataGridViewRow.Cells[1].Value.ToString();
var ping = new Ping();
PingReply result = null;
IPStatus status;
try
{
result = ping.Send(url);
status = result.Status;
}
catch (Exception ex)
{
status = IPStatus.DestinationHostUnreachable;
}
if (status != IPStatus.DestinationHostUnreachable)
{
dataGridViewRow.Cells[2].Style.BackColor = Color.Green;
}
else
{
dataGridViewRow.Cells[2].Style.BackColor = Color.Red;
}
}
}
}
}