渲染2个ListBoxes,一个包含字符串,一个包含相同字符串的长度

时间:2012-06-20 16:52:50

标签: c# winforms

public partial class Form1 : Form
{
    string[] names = new string [20]                  

  {"John","Susy","Obedia","Saul","Abram","Lincoln","Abraham","Eli","Kain","Abel",                                    


   "Will","Smitty","Scott","Julie","Ramona","Melissa","Todd","Lilly","Naomi","Leland"};

    public Form1()
    {
        InitializeComponent();
    }

    private void Form1_Load(object sender, EventArgs e)
    {
        //Question #1 Pop Names in listbox
        for (int i = 0; i < names.Length; i++)
        {
            listBox1.Items.Add(names[i]);
        }
    }

这是我填充listbox1的方式,但现在listbox2我要显示每个名字的长度。我想知道如何在C#代码中找到它?

2 个答案:

答案 0 :(得分:1)

您可以使用以下代码:

private void Form1_Load(object sender, EventArgs e)
{
    //Question #1 Pop Names in listbox
    for (int i = 0; i < names.Length; i++)
    {
        listBox1.Items.Add(names[i]);
        listBox2.Items.Add(names[i].Length);
    }
}

答案 1 :(得分:0)

这看起来像是家庭作业,所以我不会放弃完整的答案。

您希望使用C#中的String.Length属性来获取每个名称的长度。

string str = "Michael";
int len = str.Length;

现在,您可以选择是从listBox1本身编译属性,还是选择原始数组并迭代它。