如何将文本框值添加到数组并仅显示填充的数组位置?
How to add textbox value to array and display only the filled array places?
我有一个数组,它的大小是 100。所以它是这样的:
string[] Brands = new string[100];
我的 Form
上也有一个 TextBox
。每次单击 Button
时,我都希望 TextBox
将其数据存储在数组中。之后,我希望数组将值显示为 ListBox
。但是,我只希望 ListBox
显示数组实际使用的内存。所以我在数组中有 100 个位置,但我只想显示使用过的。
有人可以帮我吗?
int ArrayPos = 0;
string[] Brands = new string[100];
private void Button_Click(object sender, RoutedEventArgs e)
{
if(arrayPos < 100)
{
Brands[ArrayPos] = textBox.Text;
listbox.add(Brands[ArrayPos]);
ArrayPos++;
}
};
这将允许您将项目添加到数组的下一个位置,并检查数组是否未满。然后它会将新填充的数组位置的内容添加到列表框中。
如果您改用 List<string>
,您尝试做的事情会容易得多。
List<string> Brands = new List<string>();
当您点击按钮时,您可以像这样将您的元素添加到列表中:
Brands.Add(textBox1.Text);
当你想显示元素的数量时(我假设这就是你所说的 "actual used memory" 的意思),就像引用 Count
属性:
int totalBrands = Brands.Count;
如果出于某种原因您有强制使用 string[100]
的约束,这将不起作用。
根据限制,如果你只能使用数组,你可能需要这样的东西
int index = 0; //to tell the current position of the array "pointer"
string[] Brands = new string[100];
//And on your Button click event
private void button1_Click(object sender, EventArgs e) {
if (index < Brands.Length) {
Brands[index] = textBox1.Text;
listBox1.Items.Add(Brands[index++]);
}
}
通过这种方式,您可以在单击 button1
事件时将 textBox1
中的任何内容添加到数组中由 index
值指向的位置。只要您的 index
不大于 Brands.Length
,您始终可以使用 listBox1.Items.Add
.
将项目添加到您的 listBox1
我有一个数组,它的大小是 100。所以它是这样的:
string[] Brands = new string[100];
我的 Form
上也有一个 TextBox
。每次单击 Button
时,我都希望 TextBox
将其数据存储在数组中。之后,我希望数组将值显示为 ListBox
。但是,我只希望 ListBox
显示数组实际使用的内存。所以我在数组中有 100 个位置,但我只想显示使用过的。
有人可以帮我吗?
int ArrayPos = 0;
string[] Brands = new string[100];
private void Button_Click(object sender, RoutedEventArgs e)
{
if(arrayPos < 100)
{
Brands[ArrayPos] = textBox.Text;
listbox.add(Brands[ArrayPos]);
ArrayPos++;
}
};
这将允许您将项目添加到数组的下一个位置,并检查数组是否未满。然后它会将新填充的数组位置的内容添加到列表框中。
如果您改用 List<string>
,您尝试做的事情会容易得多。
List<string> Brands = new List<string>();
当您点击按钮时,您可以像这样将您的元素添加到列表中:
Brands.Add(textBox1.Text);
当你想显示元素的数量时(我假设这就是你所说的 "actual used memory" 的意思),就像引用 Count
属性:
int totalBrands = Brands.Count;
如果出于某种原因您有强制使用 string[100]
的约束,这将不起作用。
根据限制,如果你只能使用数组,你可能需要这样的东西
int index = 0; //to tell the current position of the array "pointer"
string[] Brands = new string[100];
//And on your Button click event
private void button1_Click(object sender, EventArgs e) {
if (index < Brands.Length) {
Brands[index] = textBox1.Text;
listBox1.Items.Add(Brands[index++]);
}
}
通过这种方式,您可以在单击 button1
事件时将 textBox1
中的任何内容添加到数组中由 index
值指向的位置。只要您的 index
不大于 Brands.Length
,您始终可以使用 listBox1.Items.Add
.
listBox1