【问题标题】:C# Windows Form: Associating a text box each with selected ListBox ItemC# Windows 窗体:将每个文本框与选定的 ListBox 项相关联
【发布时间】:2018-02-10 13:12:10
【问题描述】:

我创建了一个包含大约 12 个项目的 CheckedListBox。我想动态创建文本框,以在每次选择项目时在表单上显示和接受用户的输入值。 Textboxes 值将与 Selected Items 值相关联,以便在最终选择 Button 时存储到某些 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;
    }

我做错了什么?

你能帮忙吗?

【问题讨论】:

  • 它们都在彼此之上,您必须选择另一个位置或使用 FlowLayoutPanel。使用单独的文本框创建自己的网格控件很少会出错,始终优先使用 DataGridView。

标签: c# winforms dynamic controls


【解决方案1】:

您为所有文本框设置了相同的位置。 尝试设置如下内容:

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

【讨论】:

  • 感谢您的意见。即使设置了 txtBoxes[i].Location = new Point(450 + x*20, 100);,其他文本框仍然没有显示
  • 我犯了一个错误,你应该乘以 i 而不是 x。所以使用这个:txtBoxes[i].Location = new Point(450 + i*20, 100);
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-09-21
  • 2012-01-23
相关资源
最近更新 更多