C# 从列表框到消息框的选定索引

C# 从列表框到消息框的选定索引,c#,winforms,C#,Winforms,可能重复: 我正在编写一个程序,要求用户为他们的房子或公寓输入七个不同的参数。提交信息时,输入的地址进入列表框。当用户单击单独的按钮时,七个参数应显示在消息框中。我已经有了一个名为DisplayInfo()的方法,当调用它时,它将在列中显示信息,因此我只需要它的选定索引部分的帮助 public virtual string DisplayInfo() { return string.Format("Property ID: {0}\nProperty Address: {1}\nYear

可能重复:

我正在编写一个程序,要求用户为他们的房子或公寓输入七个不同的参数。提交信息时,输入的地址进入列表框。当用户单击单独的按钮时,七个参数应显示在消息框中。我已经有了一个名为DisplayInfo()的方法,当调用它时,它将在列中显示信息,因此我只需要它的选定索引部分的帮助

public virtual string DisplayInfo()
{
  return string.Format("Property ID: {0}\nProperty Address: {1}\nYear Built: {2}\nNumber of Bedrooms: {3}\nSquare Footage: {4}\nPrice: {5}",
    GetID(),
    GetAddress(),
    GetYearBuilt(),
    GetBedrooms(),
    GetSquareFootage(),
    GetPrice());
}

对于按钮,连接
单击
事件:

public Form1() {
  InitializeComponent();
  button1.click += new EventHandler(button1_Click);
}

void button1_Click(object sender, EventArgs e) {
  if (listBox1.SelectedIndex > -1) {
    MessageBox.Show(DisplayInfo());
  }
}

对于按钮,连接
单击
事件:

public Form1() {
  InitializeComponent();
  button1.click += new EventHandler(button1_Click);
}

void button1_Click(object sender, EventArgs e) {
  if (listBox1.SelectedIndex > -1) {
    MessageBox.Show(DisplayInfo());
  }
}

hi在listbox的selectedIndex change event方法上调用“DisplayInfo”方法


hi在listbox的selectedIndex change event方法上调用“DisplayInfo”方法


这是webforms还是winforms?这是一个c#windows窗体应用程序这是webforms还是winforms?这是一个c#windows窗体应用程序出于某种原因,我的DisplayInfo方法没有出现?@jamesclemens你必须向我们展示你的
DisplayInfo
方法。哦,还要学会接受答案并在有用的帖子上投票。查看而不是更改SelectedIndex下的代码,它不应该在“Show公寓”按钮下吗?@jamesclemens嗯,我从这里看不到您的程序。我看到你用一些代码编辑了你的文章。是,将
DisplayInfo
移动到按钮的单击事件。代码没有显示的是所有函数正在执行的操作:
GetID()
GetAddress()
。这些函数大概应该使用
listBox1.SelectedIndex
listBox1.SelectedItem
listBox1.SelectedValue
调用,这取决于您如何设置数据。这是我已经做过的,但这只是一个接一个地显示消息框,而不仅仅是所选项目//私有void AddApartmentToListBox()//{//lstplation.Items.Clear();//foreach(家中的公寓人员)//{//{//lstplation.Items.Add(persons.GetAddress());//}//},我的DisplayInfo方法没有显示?@jamesclemens您必须向我们显示您的
DisplayInfo
方法。哦,还要学会接受答案并在有用的帖子上投票。查看而不是更改SelectedIndex下的代码,它不应该在“Show公寓”按钮下吗?@jamesclemens嗯,我从这里看不到您的程序。我看到你用一些代码编辑了你的文章。是,将
DisplayInfo
移动到按钮的单击事件。代码没有显示的是所有函数正在执行的操作:
GetID()
GetAddress()
。这些函数大概应该使用
listBox1.SelectedIndex
listBox1.SelectedItem
listBox1.SelectedValue
调用,这取决于您如何设置数据。这是我已经做过的,但这只是一个接一个地显示消息框,而不仅仅是所选项目//private void AddApartmentToListBox()//{//{lstplation.Items.Clear();///foreach(家中的公寓人员)//{//{//lstplation.Items.Add(persons.GetAddress());//}/}/}出于某种原因DisplayInfo()不是选项?出于某种原因DisplayInfo()不是选项?
Protected Void listBox1_SelectedIndexChanged(object sender, EventArgs e)
{
  if(listBox1.SelectedIndex!=-1)
  { 
     DisplayInfo(listBox1.SelectedItem.ToString());
  }
}