Tutorial :Creating an Inputbox in C# using forms



Question:

Hello I'm currently creating an application which has the need to add server IP addresses to it, as there is no InputBox function in C# I'm trying to complete this using forms, but am very new to the language so not 100% as to what I should do.

At the moment I have my main form and a form which will act as my inputbox which wants to hide on load. Then when the user clicks on the add IP Address on the main form I wish to open up the secondary form and return the IP address entered into a text box on the secondary form.

So how would I go about doing this? Or is there any better ways to achieve similar results?


Solution:1

In your main form, add an event handler for the event Click of button Add Ip Address. In the event handler, do something similar as the code below:

private string m_ipAddress;  private void OnAddIPAddressClicked(object sender, EventArgs e)  {      using(SetIPAddressForm form = new SetIPAddressForm())      {          if (form.ShowDialog() == DialogResult.OK)          {              //Create a property in SetIPAddressForm to return the input of user.              m_ipAddress = form.IPAddress;          }      }  }  

Edit: Add another example to fit with manemawanna comment.

private void btnAddServer_Click(object sender, EventArgs e)  {      string ipAdd;      using(Input form = new Input())      {          if (form.ShowDialog() == DialogResult.OK)          {              //Create a property in SetIPAddressForm to return the input of user.              ipAdd = form.IPAddress;          }      }  }  

In your Input form, add a property:

public class Input : Form  {      public string IPAddress      {          get { return txtInput.Text; }      }        private void btnInput_Click(object sender, EventArgs e)      {          //Do some validation for the text in txtInput to be sure the ip is well-formated.            if(ip_well_formated)          {              this.DialogResult = DialogResult.OK;              this.Close();          }      }  }  


Solution:2

I've needed this feature, too. Here's my code; it auto-centers and sizes to fit the prompt. The public method creates a dialog and returns the user's input, or null if they cancel.

using System;  using System.Drawing;  using System.Windows.Forms;    namespace Utilities  {  public class InputBox      {      #region Interface      public static string  ShowDialog(string prompt, string title, string defaultValue = null, int? xPos = null, int? yPos = null)          {          InputBoxDialog  form   = new InputBoxDialog(prompt, title, defaultValue, xPos, yPos);          DialogResult    result = form.ShowDialog();          if (result == DialogResult.Cancel)              return null;          else              return form.Value;          }      





        
Previous
Next Post »