关于ListBox选中值的问题
例子:在ListBox显示本地ip地址 ,取出选中值。
From1:中点击Button1弹出 From2。
public partial class From1 : Form
{
public From1()
{
InitializeComponent();
}
From2 f2 = new From2();
private void Button1_Click(object sender, EventArgs e)
{
f2.StartPosition = FormStartPosition.CenterScreen;//弹出窗口居中;
f2.ShowDialog();
}
}
From2:ListBox显示ip
public partial class From2: Form
{
public From2()
{
InitializeComponent();
}
private void listBox1_MouseClick(object sender, MouseEventArgs e) //ListBox选中ip值
{
int index = listBoxip.IndexFromPoint(e.X, e.Y);
listBoxip.SelectedIndex = index;
if (listBoxip.SelectedIndex != -1)
{
MessageBox.Show("选择的ip:" + listBoxip.SelectedItem.ToString());
}
}
public string GetSelectIP() //获取选中的ip
{
return listBoxip.SelectedItem.ToString();
}
private void IPSelectFrom_Load(object sender, EventArgs e)
{
GetAllIP();
}
public void GetAllIP() //获取本机所有IPV4地址
{
try
{
string HostName = Dns.GetHostName(); //得到主机名
IPHostEntry IpEntry = Dns.GetHostEntry(HostName);
for (int i = 0; i < IpEntry.AddressList.Length; i++)
{
//从IP地址列表中筛选出IPv4类型的IP地址
//AddressFamily.InterNetwork表示此IP为IPv4,
//AddressFamily.InterNetworkV6表示此地址为IPv6类型
if (IpEntry.AddressList[i].AddressFamily == AddressFamily.InterNetwork)
{
listBoxip.Items.Add(IpEntry.AddressList[i].ToString());
}
}
}
catch (Exception ex)
{
MessageBox.Show("获取本机IP出错:" + ex.Message);
}
}
private void button1_Click_1(object sender, EventArgs e) //点击关闭 From2 窗口
{
// CListBox::ResetContent();
this.Close();
}