【问题标题】:Selected index from listbox to messagebox [duplicate]从列表框到消息框的选定索引[重复]
【发布时间】:2012-04-18 01:20:52
【问题描述】:

可能重复:
Displaying information in messagebox from listbox

我正在编写一个程序,要求用户为他们的房子或公寓输入七个不同的参数。提交信息后,输入的地址将进入列表框。当用户单击单独的按钮时,七个参数应显示在消息框中。我已经有一个名为 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());
}

【问题讨论】:

  • 这是 webforms 还是 winforms ?
  • 它是一个 c# windows 窗体应用程序

标签: c# winforms


【解决方案1】:

对于按钮,连接Click 事件:

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

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

【讨论】:

  • 由于某种原因,我的 DisplayInfo 方法没有出现?
  • @jamesclemens 你必须向我们展示你的DisplayInfo 方法。哦,学习接受答案并对有用的帖子进行投票。见FAQ
  • 而不是在SelectedIndexChanged下有代码,不应该在“显示公寓”按钮下吗?
  • @jamesclemens 好吧,我从这里看不到你的程序。我看到你用一些代码编辑了你的帖子。是的,将您的DisplayInfo 移动到按钮的单击事件中。你的代码没有显示的是你所有的函数正在做什么:GetID()GetAddress()。根据您设置数据的方式,这些函数可能应该使用listBox1.SelectedIndexlistBox1.SelectedItemlistBox1.SelectedValue 调用。
  • 这是我已经拥有的,但这只是显示一个又一个的消息框,而不仅仅是选定的项目。 //private void AddApartmentToListBox() //{ // lstApartment.Items.Clear(); // foreach(家庭中的公寓人员) // { // lstApartment.Items.Add(persons.GetAddress()); // } //}
【解决方案2】:
if(lbox.SelectedItem != null)
 {
    DisplayInfo(lbox.SelectedItem);
 }

【讨论】:

    【解决方案3】:

    在列表框的 selectedIndex 更改事件方法上,您可以调用您的“DisplayInfo”方法

    Protected Void listBox1_SelectedIndexChanged(object sender, EventArgs e)
    {
      if(listBox1.SelectedIndex!=-1)
      { 
         DisplayInfo(listBox1.SelectedItem.ToString());
      }
    }
    

    【讨论】:

    • 由于某种原因 DisplayInfo() 不是一个选项?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-07-15
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多