Remove item from listbox C#

User-939069355 posted

I KNOW there are ways to remove item from database and my question is because the data is stored on BOTH the database and listbox, how am I able to do so? As in, when the user adds an item, it gets listed in the listbox and then has the choice to remove the item (which is done by selecting the item in the listbox and pressing the 'remove' button.

To remove the item from the listbox, I have a current function that does it. But Im wondering how I can remove from the database also, because to remove it from the database, I need to first select it in the table be it by its id, or name or something. However, because the item is added into a list and retrieved by my 'remove' button as a .Text, then how do I get the (eg. id) of the selected item to be passed into the SQL query to be deleted?

My currently remove button codes is this.

protected void removepromo_Click(object sender, EventArgs e)
{
if (ListBox1.SelectedItem.Text == null)
{
promovali.Text = "Please select an item for deletion.";
}
else
{
string remove = ListBox1.SelectedItem.Text;
ListBox1.Items.Remove(remove);
}
}

As you can see how the item is removed from the listbox, my question was how do I make the system retrieve the id or name of the 'remove' string and pass it into my SQL query for deletion?

User-939069355 posted

protected void BtnDeleteItem_Click(object sender, ImageClickEventArgs e)
{
for (int i = 0; i <= ListBox1.Items.Count - 1; i++)
{
if (ListBox1.Items[i].Selected)
{
RemoveItem(Convert.toint32(ListBox1.Items[i].Value));
}
}

}


//Method
private int RemoveItem(int Empid)
{
//open connection
SqlCommand MyCmd = new MySqlCommand("delete from employeetable where emp_id = "+Empid+"");
MyCmd.Connection = ConnectionString.MyCon;
MyCmd.ExecuteNonQuery();
//close connection

return 0;

}

I think I did something wrong somewhere in my codes. Im having this error.

Input string was not in a correct format.

And it points to this

removepromotion(Convert.ToInt32(ListBox1.Items[i].Value));

This is my code currently..

protected int removepromotion(int promoid) { SqlConnection conn = new SqlConnection(GetConnectionString()); string sql = "DELETE FROM promotions WHERE promoId=" + promoid + ""; conn.Open(); SqlCommand MyCmd = new SqlCommand(sql, conn); MyCmd.ExecuteNonQuery(); conn.Close(); return 0; } protected void removepromo_Click(object sender, EventArgs e) { if (ListBox1.SelectedItem.Text == null) { promovali.Text = "Please select an item for deletion."; } else { for (int i = 0; i <= ListBox1.Items.Count - 1; i++) { if (ListBox1.Items[i].Selected) { removepromotion(Convert.ToInt32(ListBox1.Items[i].Value)); } } string remove = ListBox1.SelectedItem.Text; ListBox1.Items.Remove(remove); } }Please let me know where I went wrong, thanks :)