I have created following function to call for delete the selected record from database
and also from the listbox, which will get call on button Delete Record
.
Function:
void DeleteListBox2()
{
string connstring = String.Format("Server=localhost;Port=***;" +
"User Id=****;Password=****;Database=****;");
NpgsqlConnection conn = new NpgsqlConnection(connstring);
conn.Open();
for (int i = 0; i < listBox2.SelectedItems.Count; i++)
{
var itemname = listBox2.SelectedValue;
NpgsqlCommand cmd = new NpgsqlCommand("DELETE FROM Table WHERE Value = '" + itemname + "'", conn);
cmd.ExecuteNonQuery();
MessageBox.Show("Selected record deleted from database");
listBox2.Items.Remove(listBox2.SelectedItems[i]); //ERROR LINE
listBox2.Update();
}
conn.Close();
}
ERROR:
Items collection cannot be modified when the DataSource property is set.