【问题标题】:how to get ComboBox items count如何获取 ComboBox 项目数
【发布时间】:2012-08-09 15:21:19
【问题描述】:

我正在尝试使用以下代码获取组合框项目数。它不会给出错误,也不会给出正确的计数。我想我必须将 int 转换为 string,但是如何?

ComboBox1->ItemIndex = 1;
int count = ComboBox1->Items->Count;
Edit1->Text =  "Count: " + count;

【问题讨论】:

  • 您期望计数是多少,Edit1->Text 中显示什么?您如何向 ComboBox1 添加项目以及添加了多少项目?
  • 对不起,我不知道,我现在非常适合 Embarcadero RAD Studio XE2。我已经创建了一个 VCL 应用程序
  • @shf301 它应该是 30 并且 Edit1->Text = ""
  • @Power-Mosfet 检查我的答案 - 我已经为 Embarcadero 环境量身定制了它,应该适合你

标签: c++ c++builder vcl


【解决方案1】:

这一行

 int count = ComboBox1->Items->Count; 

返回 TComboBox 中字符串项的数量。你需要在设置之前检查这个

ComboBox1->ItemIndex = 1;

as ItemIndex 用于设置组合框中的选中项,计数为零。要在 Embarcadero 中将整数转换为字符串,您可以使用 IntToStr() 函数

Edit1->Text = "Count:" + IntToStr(count)

您需要#include "System.hpp" 才能访问该功能

【讨论】:

  • 正是我想要的。谢谢。
【解决方案2】:
ComboBox1->ItemIndex = 1;
int count = ComboBox1->Items->Count;
Edit1->Text =  "Count: " + count;

这里"Count: " + count 是一个表达式,其中"Count: " 衰减为指向字符串第一个元素的指针,count 被添加到该指针,结果它要么指向字符串中的某处(OK),要么指向字符串的结尾(通常是未定义的行为)。

关于你的ComboBox1 的使用,你没有展示它的声明,你也没有提到你正在使用哪个 GUI 框架,如果有的话。

因此,如果不猜测它是什么,就无法谈论它。

为了创建带有插入文本值表示的格式化文本,您可以使用例如std::ostringstream 来自 <sstream> 标头,如下所示:

std::ostringstream stream;
stream << "Count: " << count;
Edit1->text = stream.str().c_str();

根据Edit1.text 接受的内容,可能需要也可能不需要调用.c_str()

【讨论】:

    【解决方案3】:
    ComboBox1->ItemIndex = 1; 
    int count = ComboBox1->Items->Count;
    Edit1->Text =  "Count: " + count;
    

    【讨论】:

      【解决方案4】:

      没有必要经历所有这些杂耍。为此提供了一个简单的函数。

      int count = ComboBox1.GetItemCount();
      

      【讨论】:

        猜你喜欢
        • 2015-08-14
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2013-07-11
        • 2010-10-26
        • 1970-01-01
        • 2012-11-05
        相关资源
        最近更新 更多