单击按钮后在文本字段中显示输出

时间:2012-09-28 04:53:28

标签: c# asp.net textbox

我正在使用按钮获取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显示在文本区域中,而不是消息框。

2 个答案:

答案 0 :(得分:3)

请为您的文本框命名,如

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

在后端代码中

txtMachIPNAME.Text = myIP.ToString();

答案 1 :(得分: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;
}