Look at this code how it should be done:
public partial class Form1 : Form
{
List<string> list;
BindingList<string> bindingList;
public Form1()
{
InitializeComponent();
string[] array = new string[] { "A", "B", "C" };
list = new List<string>(array);
bindingList = new BindingList<string>(list);
listBox1.DataSource = bindingList;
listBox1.SelectedIndex = -1;
}
private void button1_Click(object sender, EventArgs e)
{
string item = listBox1.SelectedItem.ToString();
bindingList.Remove(item);
}
}
Mitja Bonca
Nearly a Posting Maven
2,485 posts since May 2009
Reputation Points: 641
Solved Threads: 474
And here is the example (better suitable to you) which using dataTable (dataSet) as dataSoucrce. Take a look how it has to be done. The code automatically removed the item from listBox (becuase it was removed from dataTable and its data bound):
public partial class Form1 : Form
{
BindingSource bs;
DataSet ds;
public Form1()
{
InitializeComponent();
string[] array = new string[] { "A", "B", "C" };
ds = new DataSet();
DataTable table = new DataTable("table1");
table.Columns.Add(new DataColumn("letters", typeof(string)));
DataRow dr;
for (int i = 0; i < array.Length; i++)
{
dr = table.NewRow();
dr["letters"] = array[i];
table.Rows.Add(dr);
}
ds.Tables.Add(table);
//set datasource:
bs = new BindingSource();
bs.DataSource = ds.Tables["table1"];
listBox1.DataSource = bs;
listBox1.DisplayMember = "letters";
listBox1.ValueMember = listBox1.DisplayMember;
listBox1.SelectedIndex = -1;
}
private void button1_Click(object sender, EventArgs e)
{
int rowIndex = listBox1.SelectedIndex;
ds.Tables["table1"].Rows[rowIndex].Delete();
}
}
I hope it helps,
Mitja
Mitja Bonca
Nearly a Posting Maven
2,485 posts since May 2009
Reputation Points: 641
Solved Threads: 474
Mitja Bonca
Nearly a Posting Maven
2,485 posts since May 2009
Reputation Points: 641
Solved Threads: 474