I create a winform application that contains 3 textbox (pcno
, pcname
and pcipadd
), one listbox that is using a datasource and one button to add new item. I'm having a trouble to add an item to my listbox. I'm using this code on the add item button:
_pcno.Add(new PCNo() { PCNO = pcno.Text,
PCNAME = pcname.Text,
IPADDRESS = pcipadd.Text });
The code above adds the new item successfully, but the selected item in the listbox also been updated.
In details, I currently have a "PCN01" on my listbox. Then I go to my textbox (pcno.text
) then write new value (example "PC02") and click the button to add item .What happens is the item is added but the "PC01" are also getting updated to "PC02". After reloading the form (re-open) all change back to normal, "PC01" with its value and "PC02" with its value. I just don't want the selected item on the listbox getting update while adding the new item. Any ideas?
Ok, to put this simplly, this is what I'm trying to do, you can try it, if you add new item the selected item also getting updated:
using System;
using System.ComponentModel;
using System.Windows.Forms;
namespace PCListing
{
public partial class Form1 : Form
{
private BindingList<mylist> _pcno;
private ListBox listBox1;
private TextBox pcno;
private TextBox pcname;
private Button btnAdd;
public Form1()
{
InitializeComponent();
FlowLayoutPanel layout = new FlowLayoutPanel();
layout.Dock = DockStyle.Fill;
Controls.Add(layout);
listBox1 = new ListBox();
layout.Controls.Add(listBox1);
pcno = new TextBox();
layout.Controls.Add(pcno);
pcname = new TextBox();
layout.Controls.Add(pcname);
btnAdd = new Button();
btnAdd.Click += btnAdd_Click;
btnAdd.Text = "Add Item";
layout.Controls.Add(btnAdd);
Load += new EventHandler(Form1_Load);
}
private void Form1_Load(object sender, EventArgs e)
{
_pcno = new BindingList<mylist>();
_pcno.Add(new mylist() { pcno = "1", pcname = "PC01" });
_pcno.Add(new mylist() { pcno = "2", pcname = "PC02" });
listBox1.DisplayMember = "pcno";
listBox1.DataSource = _pcno;
pcno.DataBindings.Add("Text", _pcno, "pcno");
pcname.DataBindings.Add("Text", _pcno, "pcname");
}
private void btnAdd_Click(object sender, EventArgs e)
{
_pcno.Add(new mylist() { pcno =pcno.Text, pcname = pcname.Text });
}
public class mylist
{
public string pcname { get; set; }
public string pcno { get; set; }
}
}
}