ScareCrow
ScareCrow

Reputation: 31

Delete record from MDF database

I want to create simple application in C#. It should be windowsForms app, with service-based database added to project. In this I want to make table (ID, name, second name) and in program show name into listBox. Current name selected in listBox will be deleted (row will be deleted)

Can anyone help me how to do it? I have try with dataset, this is working, but after I close app and run it again, table is full with data again.

Upvotes: 1

Views: 2592

Answers (1)

ridoy
ridoy

Reputation: 6322

For saving records into database and loading them in a listbox you can see..

Now,for deleting a record from a listbox you can code like this..

   protected void removeButton_Click(object sender, EventArgs e)
    {
        if (ListBox1.SelectedItem.Text == null)
        {
            MessageBox.Show("Please select an item for deletion.");
        }
        else
        {
            for (int i = 0; i <= ListBox1.Items.Count - 1; i++)
            {
                if (ListBox1.Items[i].Selected)
                {
                    DeleteRecord(ListBox1.Items[i].Value.ToString());
                }
            }
            string remove = ListBox1.SelectedItem.Text;
            ListBox1.Items.Remove(remove);
        }
    }

For deleting that record also from database use like this..

private void DeleteRecord(string ID)
{
    SqlConnection connection = new SqlConnection("YOUR CONNECTION STRING");
    string sqlStatement = "DELETE FROM Table1 WHERE Id = @Id";

try
{
    connection.Open();
    SqlCommand cmd = new SqlCommand(sqlStatement, connection);
    cmd.Parameters.AddWithValue("@Id", ID);
    cmd.CommandType = CommandType.Text;
    cmd.ExecuteNonQuery();
}
catch (System.Data.SqlClient.SqlException ex)
{
    string msg = "Deletion Error:";
    msg += ex.Message;
    throw new Exception(msg);
}
finally
{
    connection.Close();
}
}

Upvotes: 3

Related Questions