C#Windows窗体:将每个文本框与选定的ListBox项关联

时间:2017-09-01 12:56:58

标签: c# winforms dynamic controls

我创建了一个大约12个项目的CheckedListBox。我想动态创建Textboxes以在每次选择Item时显示并接受表单上用户的输入值。当最终选择Button时,Textboxes值将与Selected Items Values相关联,以存储到某个Sql数据库表中。

到目前为止,我能够做到的是,即使我从列表框中选择了其他项目,也会显示一个文本框。以下是我的代码

    private void checkedList_ItemCheck(object sender, ItemCheckEventArgs e)
    {
        if (e.NewValue == CheckState.Checked)
        {
            int n = 6;
            selectedList.Items.Add(checkedList.SelectedItem.ToString());
            for (int x=0; x < checkedList.SelectedItems.Count; x++)
            {
                TextBox[] txtBoxes = new TextBox[n];
                for (int i = 0; i < n; i++)
                {
                    txtBoxes[i] = new TextBox();
                }
                for (int i = 0; i < n; i++)
                {
                this.Controls.Add(txtBoxes[i]);
                txtBoxes[i].Location = new Point(450, 100);
                txtBoxes[i].Size = new System.Drawing.Size(25, 20);
                txtBoxes[i].Validating += new CancelEventHandler(txt_Validating);
                }
            }
        }
        else
        {
            selectedList.Items.Remove(checkedList.SelectedItem.ToString());
        }

    }
    private void InitializeMyListBox()
    {
        for (int x = 0; x < selectedList.Items.Count; x++)
        {
            selectedList.SetSelected(x, true);
        }
        // Force the ListBox to scroll back to the top of the list.
        selectedList.TopIndex = 0;
    }

我做错了什么?

你能帮忙解决这个问题。

1 个答案:

答案 0 :(得分:0)

您已为所有TextBox设置了相同的位置。 尝试设置这样的东西:

txtBoxes[i].Location = new Point(450 + i*20, 100);
相关问题