我有一个简单的表单,从sql查询填充datagridview,如下所示:
private void btnGo_Click(object sender, EventArgs e)
{
var select = "SELECT top(10) CAST(CAST(substring([nSrcIPAddress], 1, 1) AS int) AS nvarchar(3)) + '.' + CAST(CAST(substring([nSrcIPAddress], 2, 1) AS int) AS nvarchar(3)) +'.' + CAST(CAST(substring([nSrcIPAddress], 3, 1) AS int) AS nvarchar(3)) +'.' + CAST(CAST(substring([nSrcIPAddress], 4, 1) AS int) AS nvarchar(3)) AS Source,CAST(CAST(substring([nDstIPAddress], 1, 1) AS int) AS nvarchar(3)) + '.' + CAST(CAST(substring([nDstIPAddress], 2, 1) AS int) AS nvarchar(3)) +'.' + CAST(CAST(substring([nDstIPAddress], 3, 1) AS int) AS nvarchar(3)) +'.' + CAST(CAST(substring([nDstIPAddress], 4, 1) AS int) AS nvarchar(3)) AS Destination, round(sum([nBytes])/1048576.0,2) AS MB FROM Source INNER JOIN SourceInterfaceMap ON Source.nSourceID = SourceInterfaceMap.nSourceID INNER JOIN FlowRaw ON SourceInterfaceMap.nInterfaceID = FlowRaw.nInputInterfaceID where sName = '" + cmbSwitch.Text + "' and (dTime > DATEADD(minute, -" + cmbPeriod.Text + ", getdate())) group by nSrcIPAddress,nDstIPAddress order by sum(nBytes) desc";
var c = new SqlConnection(@"Data Source=SQL; Database=Net; Integrated Security=SSPI");
var dataAdapter = new SqlDataAdapter(select, c);
var commandBuilder = new SqlCommandBuilder(dataAdapter);
var ds = new DataSet();
dataAdapter.Fill(ds);
foreach (DataTable table in ds.Tables)
{
foreach (DataRow row in table.Rows)
{
foreach (object item in row.ItemArray)
{
//dns here
try
{
Console.WriteLine(Dns.GetHostEntry(item.ToString()).HostName);
}
catch
{
Console.WriteLine(item);
}
}
}
dgvResults.ReadOnly = true;
dgvResults.DataSource = ds.Tables[0];
}
}
填充后的datagridview看起来像:
Source Destination MB
40.102.130.1 10.10.1.1 112.2
10.70.1.22 10.3.3.2 58.8
我要做的是查找ip并返回主机名,然后填充datagrid或循环遍历datagrid列1和2并读取值并用dns名称替换(如果可用)?
答案 0 :(得分:1)
我做了一个例子,
DataTable table = new DataTable();
table.Columns.Add("IP", typeof(string));
table.Rows.Add("127.0.0.1");
table.Rows.Add("10.70.1.22");
// generated a table at runtime to create issue quickly.
foreach(DataRow row in table.Rows) // itterate over rows
{
try
{
IPHostEntry entry = Dns.GetHostEntry(row["IP"].ToString()); // Try get host entry inside loop
row["IP"] = entry.HostName; // if GetHostEntry find HostName set it to row
}
catch(Exception) // if GetHostEntry can't find hostname it will throw error but i removed throw to not terminate the program
{
}
}
dataGridView1.DataSource = table; // set as source
希望有所帮助,