2012-09-28 120 views
2

我正在使用按钮来获取IP地址。我想在文本字段中显示该IP地址。 这是我的前端代码:单击按钮后在文本框中显示输出

<asp:TextBox ID="txtMachIP" runat="server" CssClass="Textbox1"></asp:TextBox> 
<asp:Button ID="BtnGetIP" runat="server" CssClass="btn1" 
        onclick="BtnGetIP_Click" Text="Get My IP" /> 

这是获得IP我的后端代码:

protected void BtnGetIP_Click(object sender, EventArgs e) 
{ 
    string myHost = System.Net.Dns.GetHostName(); 
    System.Net.IPHostEntry myIPs = System.Net.Dns.GetHostEntry(myHost); 
    foreach (System.Net.IPAddress myIP in myIPs.AddressList) 
    { 
     MessageBox.Show(myIP.ToString()); 

    } 
} 

相反,消息框,我想显示在文本区我的IP。

+0

Syrion,请将答案标记为已接受。 –

回答

3

请提供一个名称的文本框像

<asp:TextBox ID="txtMachIP" NAME = "txtMachIPNAME" runat="server" CssClass="Textbox1"></asp:TextBox> 

而在后端代码

txtMachIPNAME.Text = myIP.ToString(); 
+0

谢谢。像宝石一样工作! :D – Esha

+1

asp.net控件使用ID不是我想的名字。它应该是txtMachIP.Text = somevalue作为字符串 –

+0

虽然没有必要的名称。即使没有它,它也是完美的。 :) – Esha

0

一种方法是将值存储在一个临时字符串,然后输出值的最终名单文本框。

protected void BtnGetIP_Click(object sender, EventArgs e) 
{ 
    string myHost = System.Net.Dns.GetHostName(); 
    System.Net.IPHostEntry myIPs = System.Net.Dns.GetHostEntry(myHost); 
    // Create a temporary string to store the items retrieved in the loop 
string tempIPs = string.Empty; 
    foreach (System.Net.IPAddress myIP in myIPs.AddressList) 
    { 
     tempIPs += myIP.ToString() + ", "; 
    } 
    // Removes the redundant space and comma 
    tempIPs = tempIPs.TrimEnd(' ', ','); 
    // Print the values to the textbox 
    txtMachIP.Text = tempIPs; 
}