c# - 将文本框值添加到数组并将其显示在列表框中。单击按钮时刷新数组

标签 c# arrays visual-studio textbox listbox

所以我遇到了下面的问题。我有一个文本框和列表框。我做了一个这样的数组:

string[] Brands = new string[10];
            Brands[0] = "Yamaha";
            Brands[1] = "Suzuki";
            Brands[2] = "Harley";
            Brands[3] = "Kawasaki";

数组有 10 个值,但我只指定了四个值。我想通过单击按钮将最多十个值添加到此数组中。

我不能使用列表,它必须是数组。我已经发现我需要将上面的部分放在

{
    public partial class Form1 : Form        
    {

        string[] Brands = new string[10];
        Brands[0] = "Yamaha";
        Brands[1] = "Suzuki";
        Brands[2] = "Harley";
        Brands[3] = "Kawasaki";

但它无法识别 Brands[]。

private void buttonAddbrand_Click(object sender, EventArgs e)
{

需要包含将其添加到数组中的代码。就像刷新数组一样。

我卡住了,互联网上的信息太多了,每个人都建议一个列表,但我需要使用一个数组。非常感谢您的帮助。

最佳答案

你不能像这样分配数组:

public partial class Form1 : Form        
{

    string[] Brands = new string[10];
    Brands[0] = "Yamaha"; //fail
    Brands[1] = "Suzuki"; //fail
    Brands[2] = "Harley"; //fail
    Brands[3] = "Kawasaki"; //fail

在类上下文中。相反,你应该做这样的事情

public partial class Form1 : Form        
{

    string[] Brands = new string[10] { "Yamaha", "Suzuki", "Harley", "Kawasaki", "", "", "", "", "", "" };

然后,如果您将 Brands 声明为 Form1 class 字段,则在

private void buttonAddbrand_Click(object sender, EventArgs e)
{
    //Brands will be recognized
}

品牌将得到认可。如果您需要做的是向数组添加一些东西(并且您必须使用数组)。那么你还应该像这样保留当前数组中元素的数量:

public partial class Form1 : Form        
{

    string[] Brands = new string[10] { "Yamaha", "Suzuki", "Harley", "Kawasaki", "", "", "", "", "", "" };
    int brandNo = 4;

然后,当您向数组添加新项时,按如下方式进行:

private void buttonAddbrand_Click(object sender, EventArgs e)
{
    if(brandNo >= 10)
        return; //cannot add more brand
    Brands[brandNo++] = "NewBrand"; //at the brandNo AFTER you put "NewBrand", see post-increment.
}

编辑:

至于构造函数中的数组初始化,这就是你的老师想要的 - 它实际上是更长的方法。但为了教学,我还是会展示一下:

public partial class Form1 : Form        
{
    string[] Brands = new string[10];
    int brandNo; //This is a must
    public Form1(){
        InitializeComponent();
        Brands[0] = "Yamaha"; //ok
        Brands[1] = "Suzuki"; //ok
        Brands[2] = "Harley"; //ok
        Brands[3] = "Kawasaki"; //ok
        brandNo = 4; //This is a must
    }

关于c# - 将文本框值添加到数组并将其显示在列表框中。单击按钮时刷新数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34739665/

相关文章:

visual-studio - 记录对象数据的最佳技术是什么?

c# - Web Api 相同签名不同动词

java - 使用 selenium web 驱动程序可以在单个单元格中打印多个值

arrays - 如何动态设置 Rust 数组长度?

iphone - 同时在sqlite中填充数组

python - Visual Basic 开发人员想要编写 Linux 应用程序

c# - Visual Studio 调试 - native 类型

C#使用UTF8编码发送unicode短信

C# 与 MySQL - 错误 : "Guid should contain 32 digits with 4 dashes" when trying to open the connection

c# - 仅在服务器端使用证书