将数据添加到列表框?

时间:2015-03-15 22:42:00

标签: c#

我已经坚持了一段时间了,我想知道是否有办法通过表单内的文本框将数据添加到列表框中。我有一个单独的按钮,要求用户输入该列表框的数据。

这是在c#Visual studio 2012中

2 个答案:

答案 0 :(得分:0)

如果元素在同一个表单上,那么当TextBox失去焦点时,这将添加:

private void textBox_Leave(object sender, System.EventArgs e)
{
    listBox1.Items.Add(((TextBox)sender).Text);
}

如果他们不是你需要一个中间类来保存输入到TextBox的数据,然后当第二个表单加载从数据类中检索数据并将其加载到ListBox时}:

private void textBox_Leave(object sender, System.EventArgs e)
{
    _inMemoryDatabase.Add(((TextBox)sender).Text);
}

private void form2_Load(object sender, System.EventArgs e)
{
    foreach(var item in _inMemoryDatabase.GetData())
        listBox1.Items.Add(item);
}

答案 1 :(得分:0)

有很多方法可以做到这一点。我将向您展示一种简单的方法。

enter image description here

这里我有两种形式

  1. 名单(带有列表框和按钮)

  2. Form_TakingValue(带文本框和按钮)

  3. 您可以将此listBox作为参数传递给form_takingValue,以便可以在第二个表单中完成任何更改。

    名单列表表格代码

    public partial class NameList : Form
    {
        public Form2()
        {
            InitializeComponent();
        }
    
        private void btnAddNew_Click(object sender, EventArgs e)
        {
            new Form_TakingValue(listBox1).ShowDialog();
        }
    }
    

    Form_TakingValue代码

    public partial class Form_TakingValue : Form
    {
        ListBox listBox;
        public Form_TakingValue()
        {
            InitializeComponent();
        }
    
        public Form_TakingValue(ListBox lBox)  // -> Overloaded function for our needs
        {
            InitializeComponent();
            listBox = lBox;
        }
    
        private void btnOK_Click(object sender, EventArgs e)
        {
            listBox.Items.Add(txtName.Text); // this listBox belongs to the first form and we are making changes to it from here..
            Close();
        }
    }
    
相关问题