将PictureBox添加到数组中

时间:2018-04-07 05:34:39

标签: c# arrays visual-studio picturebox

我正在创建一个图片框数组,但我不确定将新图片框放入数组所需的代码。

    List<String> keyList=new ArrayList<>();
DatabaseReference myRef = FirebaseDatabase.getInstance().getReference().child("Users").child("Customers");
ValueEventListener eventListener = new ValueEventListener() {
    @Override
    public void onDataChange(DataSnapshot dataSnapshot) {
                for(DataSnapshot nodo : dataSnapshot.getChildren()) {

                    String key = nodo.getKey();
                    Log.d("TAG", key);

                /*Add all the keys to keyList here*/
                    keyList.add(key);

                }

        /*After the loop ends set the list of keys to textview like this*/
            if (keyList.size()>0)
            {
                for (String s : keyList)
                {
                mSetting.setText(mSetting.getText().toString()+"\n"+s);
                }
            }
    }

    @Override
    public void onCancelled(DatabaseError databaseError) {}

};
myRef.addListenerForSingleValueEvent(eventListener);

1 个答案:

答案 0 :(得分:0)

在代码行PictureBox[] bossHealth = new PictureBox[20];之后你有一个可容纳20个图片框的数组。但是,此数组中的每个单元格都包含null - 您必须在循环中初始化它。

此外,这一行bossHealth.Add(bossHealth[i]);毫无意义。数组没有Add方法,bossHealth[i]已经是数组的一部分。好像你正在混合数组和列表。

以下是代码的改进版本:

PictureBox[] bossHealth = new PictureBox[20];
for( int i = 0; i<19; i++)
{
    bossHealth[i] = new PictureBox();
    bossHealth[i].Name = "health";
    bossHealth[i].Size = new Size(10, 26);
    bossHealth[i].BackColor = Color.LimeGreen;
    bossHealth[i].Location = new Point(this.Width / 2 + (i * 10), 12);
    Controls.Add(bossHealth[i]);
}