Click here to Skip to main content
15,885,197 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
Hello i am working on a store made in c#. I have CRUD created and when i add a customer/product it adds it to the database without any problems. My problem is when i go to delete or modify/update a customer or product. When i do this it says the selectedindex is undefined and im not sure why. Here is what i have for code.

C#
public partial class CustomerList : Window
{
    public int selectedCustomer = -1;
    //public String selectedItem;
    public String userType;
    public Customer cust;        
    List<Customer> customers = new List<Customer>();


    public CustomerList()
    {
        InitializeComponent();
        PopulateList();

    }
    /////////////////////////////////////////////
    //// MAYBE INFO FROM DB
    private void GetCustomer(int customerID)
    {
        try
        {
            cust = CustomerDB.GetCustomer(customerID);
        }
        catch (Exception e)
        {
            MessageBox.Show(e.Message, e.GetType().ToString());
        }
    }


    private void PopulateList()
    {
        userType = null;
        CListbox.Items.Clear();            
        customers = CustomerDB.GetListCustomer();            
        foreach (Customer customer in customers)
        {                
            CListbox.Items.Add(customer.ToString());
            CListbox.Items.Add(" ");
        }
    }


    private void btnAddCustomer_Click(object sender, RoutedEventArgs e)
    {
        Console.WriteLine(cust);
        Window newDude = new CustomerAdd();
        newDude.ShowDialog();
        this.Close();
    }

    private void btnDeleteCustomer_Click(object sender, RoutedEventArgs e)
    {
        Window DeleteCustomer = new CustomerList();
        MessageBoxResult result = MessageBox.Show("Are you sure you want to Delete ",
                             "Confirm Delete", MessageBoxButton.YesNo, MessageBoxImage.Question);

        //customers
        if (result == MessageBoxResult.Yes)
        {
            try
            {
                if (selectedCustomer != -1)
                {
                    if (!CustomerDB.DeleteCustomer(customers[selectedCustomer])) 
                    {
                        MessageBox.Show("Customer not here", "Error");
                        this.GetCustomer(cust.userID);

                    }
                    PopulateList();
                }
                else
                {
                    MessageBox.Show("Hey, dunderhead!  You need to make a selection before you can delete!", "Error");
                }
            }
            catch (FormatException formatE) { MessageBox.Show(formatE.Message, formatE.GetType().ToString()); }
            catch (Exception ex) { MessageBox.Show(ex.Message, ex.GetType().ToString()); }
        }
    }

    private void btnExitCustomer_Click(object sender, RoutedEventArgs e)
    {
        this.Close();
    }


    private void btnModifyCustomer_Click(object sender, RoutedEventArgs e)
    {
        int customerIndex = CListbox.SelectedIndex;       //CListbox.SelectedIndex;
        if (customerIndex != -1)
        {
            Customer customer = (Customer)customers[customerIndex];
            string message = "Are you sure you want to edit: " + customer.firstName +
                "  " + customer.lastName + "?";

            MessageBoxResult modify = MessageBox.Show(message, "Aceept Modify", MessageBoxButton.YesNo,
                MessageBoxImage.Warning);
            if (modify == MessageBoxResult.Yes)
            {
                Window modifyCustomer = new CustomerAdd();
                modifyCustomer.Show();
            }
        }
    }
}


C#
public partial class CustomerAdd : Window
{
    public Customer cust;
    List<Customer> customers = new List<Customer>();
    public bool modify = false;

    public CustomerAdd()
    {
        InitializeComponent();
    }



    public Customer GetNewCustomer()
    {
        this.ShowDialog();
        return cust;
    }
    public void GetCustomerInformation(Customer customer)
    {
        this.cust = customer;
        this.DisplayContent();
    }
    public void DisplayContent()
    {
        txtUserID.Text = Convert.ToString(cust.userID);     //cust.userID.ToString();
        txtFirstName.Text = cust.firstName;
        txtLastName.Text = cust.lastName;
        txtAddress.Text = cust.address;
        txtCity.Text = cust.city;
        txtState.Text = cust.state;
        txtZip.Text = cust.zip;
        txtPhoneNumber.Text = cust.phoneNumber;
        txtEmail.Text = cust.email;
        txtUserName.Text = cust.userName;
        txtPassword.Text = cust.password;
        cboUserType.Text = cust.userType;   //????? cbouserType.selectedIndex ????
    }

    private void StoreClientData(Customer customer)
    {
       // cust.userID = txtUserID;
        cust.firstName = txtFirstName.Text;
        cust.lastName = txtLastName.Text;
        cust.address = txtAddress.Text;
        cust.city = txtCity.Text;
        cust.state = txtState.Text;
        cust.zip = txtZip.Text;
        cust.phoneNumber = txtPhoneNumber.Text;
        cust.email = txtEmail.Text;
        cust.userName = txtUserName.Text;
        cust.password = txtPassword.Text;
        cust.userType = cboUserType.Text;
    }


    private void btnSave_Click(object sender, RoutedEventArgs e)
    {
        if (IsValidData())
        {
            try
            {
                cust = new Customer(Convert.ToInt32(txtUserID.Text), txtFirstName.Text, txtLastName.Text, txtAddress.Text, txtCity.Text, txtState.Text, txtZip.Text,
                txtPhoneNumber.Text, txtEmail.Text, txtUserName.Text, txtPassword.Text, cboUserType.SelectedItem.ToString());
                CustomerDB.UpdateCustomer(cust);
                MessageBox.Show("Success!");
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, ex.GetType().ToString());
            }
        }
    }


    private bool IsValidData()
    {
        return Validator.IsPresent(txtFirstName) && Validator.IsPresent(txtLastName) && Validator.IsPresent(txtAddress) &&
            Validator.IsPresent(txtCity) && Validator.IsPresent(txtState) && Validator.IsInt32(txtZip) && Validator.IsPresent(txtPhoneNumber) &&
            Validator.IsPresent(txtEmail);
    }


    private void btnExit_Click(object sender, RoutedEventArgs e)
    {
        this.Close();
    }

    private void btnAdd_Click(object sender, RoutedEventArgs e)
    {
        if (IsValidData())
        {
            cust = new Customer(txtFirstName.Text, txtLastName.Text, txtAddress.Text,
                            txtCity.Text, txtState.Text, txtZip.Text, txtPhoneNumber.Text, txtEmail.Text,
                            txtUserName.Text, txtPassword.Text, cboUserType.Text);
            CustomerDB.AddNewCustomer(cust);

            Window theForm = new CustomerList();
            theForm.Show();
            this.Close();
        }
    }
}



C#
class CustomerDB
{


    //  SQL CONNECTION CODE USED
    ///////////////////////////////////////////////////////////////////////
    List<string> myList = new List<string>();

    // Retrieve the connection string from the settings file.
    // Your connection string name will end in "ConnectionString"
    // So it could be coolConnectionString or something like that.

    //private static string connString = @"Data Source=../MyDatabase.sdf";
    //@"Data Source=../MyDatabase.sdf"
    //private static SqlCeConnection conn = new SqlCeConnection(connString);

   // private static SqlCeCommand cmd = new SqlCeCommand();     //("SELECT * FROM Test", conn);

    //private static SqlCeDataReader reader = null;





    //public static void AddNewCustomer(Customer customer)
    public static void AddNewCustomer(Customer customer)
    {
        SqlCeConnection connection = MusicDB.GetSqlCeConnection();
        string insertStatement = "INSERT INTO Users " +            
            "(firstName, lastName, address, city, state, zip, phoneNumber, email, userName, password, userType)" +
            "VALUES (@firstName, @lastName , @address, @city, @state, @zip, @phoneNumber, @email, @userName, @password, @userType)";

        SqlCeCommand insertCommand = new SqlCeCommand(insertStatement, connection);
        insertCommand.Parameters.AddWithValue("@firstName", customer.firstName);
        insertCommand.Parameters.AddWithValue("@lastName", customer.lastName);
        insertCommand.Parameters.AddWithValue("@address", customer.address);
        insertCommand.Parameters.AddWithValue("@city", customer.city);
        insertCommand.Parameters.AddWithValue("@state", customer.state);
        insertCommand.Parameters.AddWithValue("@zip", customer.zip);
        insertCommand.Parameters.AddWithValue("@phoneNumber", customer.phoneNumber);
        insertCommand.Parameters.AddWithValue("@email", customer.email);
        insertCommand.Parameters.AddWithValue("@userName", customer.userName);
        insertCommand.Parameters.AddWithValue("@password", customer.password);
        insertCommand.Parameters.AddWithValue("@userType", customer.userType);

        try
        {
            connection.Open();
            insertCommand.ExecuteNonQuery();
            //string selectStatement = "SELECT @@IDENTITY FROM Users";
            //SqlCeCommand selectCommand = new SqlCeCommand(selectStatement, connection);
            //int userID = Convert.ToInt32(selectCommand.ExecuteScalar());
           // return userID;
        }
        catch (SqlCeException sqlexception)
        {
            sqlexception.Message.ToString();
            throw sqlexception;

        }
        catch (Exception ex)
        {
            ex.Message.ToString();
            //return -1;
        }
        finally
        {
            connection.Close();
        }
    }


    public static Customer GetCustomer(int userID)
    {
        SqlCeConnection conn = MusicDB.GetSqlCeConnection();
        conn.Open();
        string selectStatement = "SELECT userID, firstName, lastName, address, "+
        "city, state, zip, phoneNumber, email, userName, password, userType "+
        "FROM Users "+
        "WHERE userID = @userID";
        SqlCeCommand selectCommand = new SqlCeCommand(selectStatement, conn);
        selectCommand.Parameters.AddWithValue("@userID", userID);
            try
            {
                SqlCeDataReader customerReader = 
                    selectCommand.ExecuteReader(CommandBehavior.SingleRow);
                if(customerReader.Read())
                {
                    Customer cust = new Customer();
                    cust.userID=Convert.ToInt32(customerReader["userID"]);
                    cust.firstName=customerReader["firstName"].ToString();
                    cust.lastName=customerReader["lastName"].ToString();
                    cust.lastName=customerReader["address"].ToString();
                    cust.lastName=customerReader["city"].ToString();
                    cust.lastName=customerReader["state"].ToString();
                    cust.lastName=customerReader["zip"].ToString();
                    cust.lastName=customerReader["phoneNumber"].ToString();
                    cust.lastName=customerReader["email"].ToString();
                    cust.lastName=customerReader["userName"].ToString();
                    cust.lastName=customerReader["password"].ToString();
                    cust.lastName=customerReader["userType"].ToString();
                return cust;
                }
                else
                {
                    return null;
                }
            }
            catch(SqlCeException e)
              {
                    throw e;
              }
            finally {   conn.Close();   }
    }

    public static void UpdateCustomer(Customer customer)
    {
        SqlCeConnection connection = MusicDB.GetSqlCeConnection();

        string updateStatement = "UPDATE Users SET " +
            "firstName = @newfirstName, lastName = @newlastName, address = @newaddress, city = @newcity " +
            "state = @newstate, zip = @newzip, phoneNumber = @newphoneNumber, email = @newemail " +
            "userName = @newuserName, password = @newpassword, userType = @newuserType" +
            "WHERE userID = @userID";

        SqlCeCommand updateCommand = new SqlCeCommand(updateStatement, connection);
        updateCommand.Parameters.AddWithValue("@userID", customer.userID);
        updateCommand.Parameters.AddWithValue("@newfirstName", customer.firstName);
        updateCommand.Parameters.AddWithValue("@newlastName", customer.lastName);
        updateCommand.Parameters.AddWithValue("@newaddress", customer.address);
        updateCommand.Parameters.AddWithValue("@newcity", customer.city);
        updateCommand.Parameters.AddWithValue("@newstate", customer.state);
        updateCommand.Parameters.AddWithValue("@newzip", customer.zip);
        updateCommand.Parameters.AddWithValue("@newphoneNumber", customer.phoneNumber);
        updateCommand.Parameters.AddWithValue("@newemail", customer.email);
        updateCommand.Parameters.AddWithValue("@newuserName", customer.userName);
        updateCommand.Parameters.AddWithValue("@newpassword", customer.password);
        updateCommand.Parameters.AddWithValue("@newuserType", customer.userType);
        try
        {
            connection.Open();
            updateCommand.ExecuteNonQuery();
        }
        catch (SqlCeException sqlexception)
        {
            sqlexception.Message.ToString();
            throw sqlexception;
        }
        catch (Exception e)
        {
            e.Message.ToString();
        }
        finally
        {
            connection.Close();
        }
    }


    public static bool DeleteCustomer(Customer customer)
    {
        SqlCeConnection connection = MusicDB.GetSqlCeConnection();
        string deleteStatement = "DELETE FROM Users "+
            "WHERE userID = @userID AND firstName = @firstName AND lastName=@lastName AND address=@address "+
            "AND city=@city AND state=@state AND zip=@zip AND phoneNumber=@phoneNumber AND email=@email "+
            "AND userName=@userName AND password=@password AND userType=@userType"; 
        SqlCeCommand deleteCommand = new SqlCeCommand(deleteStatement, connection);
        deleteCommand.Parameters.AddWithValue("@userID", customer.userID);
        deleteCommand.Parameters.AddWithValue("@firstName", customer.firstName);
        deleteCommand.Parameters.AddWithValue("@lastName", customer.lastName);
        deleteCommand.Parameters.AddWithValue("@address", customer.address);
        deleteCommand.Parameters.AddWithValue("@city", customer.city);
        deleteCommand.Parameters.AddWithValue("@state", customer.state);
        deleteCommand.Parameters.AddWithValue("@zip", customer.zip);
        deleteCommand.Parameters.AddWithValue("@phoneNumber", customer.phoneNumber);
        deleteCommand.Parameters.AddWithValue("@email", customer.email);
        deleteCommand.Parameters.AddWithValue("@userName", customer.userName);
        deleteCommand.Parameters.AddWithValue("@password", customer.password);
        deleteCommand.Parameters.AddWithValue("@userType", customer.userType);
        try
        {
            connection.Open();
            int count = deleteCommand.ExecuteNonQuery();
            if (count > 0) return true;
            else return false;
        }
        catch (SqlCeException sqlexception)
        {
            sqlexception.Message.ToString();
            throw sqlexception;
        }
        catch (Exception e)
        {
            e.Message.ToString();
            return false;
        }
        finally
        {
            connection.Close();
        }
    }

    public static List<Customer> GetListCustomer()
    {
        List<Customer> customers = new List<Customer>();

        SqlCeConnection connection = MusicDB.GetSqlCeConnection();
        string selectall = "SELECT * FROM Users";
        SqlCeCommand command = new SqlCeCommand(selectall, connection);

        try
        {
            connection.Open();
            SqlCeDataReader reader = command.ExecuteReader();
            while (reader != null && reader.Read())
            {
                Customer newGuy = new Customer();
                newGuy.userID = Int32.Parse(reader["userID"].ToString());
                newGuy.firstName = reader["firstName"].ToString();
                newGuy.lastName = reader["lastName"].ToString();
                newGuy.address = reader["address"].ToString();
                newGuy.city = reader["city"].ToString();
                newGuy.state = reader["state"].ToString();
                newGuy.zip = reader["zip"].ToString();
                newGuy.phoneNumber = reader["phoneNumber"].ToString();
                newGuy.email = reader["email"].ToString();
                newGuy.userName = reader["userName"].ToString();
                newGuy.password = reader["password"].ToString();
                newGuy.userType = reader["userType"].ToString();
                customers.Add(newGuy);
            }
            reader.Close();
        }
        catch (Exception e)
        {
            throw e;
        }
        finally
        {
            connection.Close();
        }
        return customers;
    }
Posted
Comments
PIEBALDconsult 9-Dec-13 19:04pm    
I'm not digging through all that. Could you post only the code that has the problem please?


"I have CRUD created" is likely your problem.
TheBigBearNow 9-Dec-13 19:17pm    
My error that i'm currently working on is the DELETE button. when i click on a item in my list-box then click delete it is suppose to delete that selected item. Well instead it says "Index was out of range. Must be non-negative and less than the size of the collection" that is my exception that i get. My database is SQLServerCE with a list of Customers and also the list of Products.

The code i have is a listbox with some buttons ADD DELETE MODIFY AND EXIT. (CustomerList())
when you click ADD it brings up a window with text boxes which is the input form (CustomerAdd())
CustomerDB is all of my database code CRUD
PIEBALDconsult 9-Dec-13 19:35pm    
And where in your code does that happen?
TheBigBearNow 9-Dec-13 20:07pm    
In CustomerDB im calling my "public static bool DeleteCustomer(Customer customer)" in my DELETE button in CustomerList() window
I go to my listbox and click on a customer then i click delete to delete it but it says i have not selected anything. my listbox isnt noticing my selection on a particular customer and that is my question. I dont know why it doesnt know what i choose. I'm not sure what to do to fix this. I know once i can figure out how to select a item in my listbox i should be able to do my modify fairly easy. Delete and Modify im having the same error. Selecting a customer
PIEBALDconsult 9-Dec-13 20:19pm    
So then about 90% of the code you posted is irrelevent to the problem?

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900