Link to home
Start Free TrialLog in
Avatar of linkcube1
linkcube1

asked on

Editing Items in a ListView

Hello, I am trying to edit items from a listView. I want to press an edit button and have a form appear that populates all the text boxes on that form from the row selected on a listView. I attempted my code below which returns a specific item from a row when that specific row is hardcoded. I'm looking for something generic that grabs the row and allows me to get the data from it somehow I'm all out of ideas.. So please any help would be appreciated.
private void btnEdit_Click(object sender, EventArgs e)
        { 
            if (listView1.SelectedItems.Count > 0)
            {               
                mb.Author = listView1.Items[1].SubItems[3].Text;            
                mb.Description = listView1.Items[0].SubItems[3].Text;
                mb.Condition = listView1.Items[0].SubItems[5].Text;
                frmNewItem editFrm = new frmNewItem(mb);
                editFrm.GetNewBook();    
                LoadDataInListView();
            }
        }

Open in new window

Avatar of QPR
QPR
Flag of New Zealand image

You could populate a formview with the selected row from the listview?
Avatar of linkcube1
linkcube1

ASKER

well.. what I'm really looking for is taking the row and using the different items in the row as values and passing the values as text into another form to edit them
you are exactly describing what a formview is/does or am I misreading something?
Your probably right, But Could I get a different example something to relate to my listView1 shown in my code if possible? Your link made a little sense but I'm not sure how to add it to my code.
If you have VS open... try this for a demo.
Drag a form view onto your page, step through the wizard and specify a connection string (prob same as your listview) and a select statement (or even better stored procedure) that will get your single row from the database.
In the parameter step of the wizard, specify "control" and then select the name of your listview.
What you've done to this point is to say that you want to populate the formview with the relevant row from the Db where the id (or whatever you use) matches that selected in the listview.

All going well the user will see this row in the formview as readonly labels. They will have an edit button (or link) which they can click which will turn these labels into text boxes so the user can edit the row data. When they click update the values will be passed back to the database as an update statement (which you'll have to cater for with an UPDATE sql statement or stored procedure)

Have a go and let me know how you get on.

If you used a gridview to show the initial rows, you know the user could edit the data right there in that control don't you? Would cut down on the other steps
Avatar of Dmitry G
Honestly, the conversation is a bit strange, or I'm too tired and can't think :)

It seems linkcube1 talks about Win forms stuff and QPR - about web stuff. Am I right?

Advice to all askers: tell if you use winforms or web (asp)

If I'm right, it would be nice to know how generic" code should be. I mean - you want any object structure to be displayed on a form? I.e. form has to be generated on a fly?

I think this is what you are looking for
private void btnEdit_Click(object sender, EventArgs e)
        { 
            if (listView1.SelectedItems.Count > 0)
            {            
                ListViewItem item = listView1.SelectedItems[0];   
                mb.Author = item Text;            
                mb.Description = item SubItems[3].Text;
                mb.Condition = item .SubItems[5].Text;
                frmNewItem editFrm = new frmNewItem(mb);
                editFrm.GetNewBook();    
                LoadDataInListView();
            }
        }

Open in new window

yeah "ListViewItem item = listView1.SelectedItems[0]; " thats the line I needed to have things make sense, This listbox is from a select query, I would require an update query to edit the items from the form when it opens am I correct? If so would it just be
 update this, this, this, where DB = ListView.selectitems?  

and sorry.. this is a windows form not web
oops sorry! for some reason (because it's mostly what I do) I assumed we were talking web.
Ignore my posts :)
OK, at least I introduced some clarity :)

So, mkobrin's anser is OK or we need to keep thinking :)
Just one more thing, How would I update that line i selected that populated my new form into sql?

EX  = update this, this, this, where DB = ListView.selectitems?  
What I normally do is create a class for the object that I am working with, it looks like you may have done this with the object instance called md.

One I have set the properties for the object I create an instance of the form to update the record (the form has a public declatation of the same object), and then I set the public object equal to the object that I have just set. Once the user clicks on the save button on the form, I set the public object properties to the values entered on the form (after having done any validation necessary) and then set the dialog result property of my form to OK and close the form.

When the control returns to the caller the caller checks the dialog result property, and if it is OK, I call a new SQL command to update the record with the new values of the object, and then refresh my listview.

Let me know if you would like me to post some example code to do this.

(by the way, I do all my SQL calls in a seperate SQL repository class)

Mike.
An example would be great, just showing how to update at the selected index in a listview I have, the form is already populated so when I click the save button I would like it to update thanks
Here is a very small example of what I was referring to.

When you return from the caller what you need to do is set your mb object = the public mb object in your form after you have clicked the save button and then set the DialogResult = OK, then call a procedure that will save you mb object according to the properties you have no set in the object, and then refresh your listview, I do my refresh in its own procedure which I have called popLV.

I hope this helps.

Mike


//This is the code behind my save button on my form after the validation is complete
DeclineReason = textBox1.Text; //DeclineReason is a public string in this form 
//you could also use a class and set the individual properties of that class here
this.DialogResult = DialogResult.OK;//This sets the dialog result for my caller to see

//This is the code where I call the update form and then save the result
using (frmReason reason = new frmReason()) //Create an instance of the form
{
     reason.DeclineReason = "Not declined"; //Set the string (or class)
     if (reason.ShowDialog(this) == DialogResult.OK) //Show my form and read the dialog result when it closes
     {
           saveIONumber(reason.DeclineReason); //Call my save procedure
           popLV(); //Repopulate the listview.
      }
}

Open in new window

Yes that all makes sense thanks, But im looking for the actually SQL code to update the mb object I tried this but not having alot of luck.

public static bool UpdateMemberBook(MemberBook oldMB,
        MemberBook newMB)
        {
            SqlConnection connection = MMABooksDB.GetConnection();
            string updateStatement =
                "UPDATE MemberBookInventory SET " +
                "Title = @NewTitle, " +
                "Author = @NewAuthor, " +
                "ISBNNumber = @NewISBNNumber, " +
                "Description= @NewDescription, " +
                "Condition= @NewCondition, " +
                "Price = @NewPrice, " +
                "MemberID = @NewMemberID " +
                "WHERE Title = @OldTitle " +
                "AND Author = @OldAuthor " +
                "AND ISBNNumber = @OldISBNNumber " +
                "AND  Description = @OldDescription " +
                "AND  Condition = @OldCondition" +
                "AND  Price = @OldPrice " +
                "AND MemberID = @OldMemberID";                             
            SqlCommand updateCommand =
                new SqlCommand(updateStatement, connection);
            updateCommand.Parameters.AddWithValue(
                "@NewTitle", newMB.Title);
            updateCommand.Parameters.AddWithValue(
                "@NewAuthor", newMB.Author);
            updateCommand.Parameters.AddWithValue(
                "@NewISBNNumber", newMB.ISBNNumber);
            updateCommand.Parameters.AddWithValue(
                "@NewDescription", newMB.Description);
            updateCommand.Parameters.AddWithValue(
                "@NewCondition", newMB.Condition);
            updateCommand.Parameters.AddWithValue(
                "@NewMemberID", newMB.Member.MemberID);
            updateCommand.Parameters.AddWithValue(
                "@NewPrice", newMB.Price);
            updateCommand.Parameters.AddWithValue(
                "@OldTitle", oldMB.Title);
            updateCommand.Parameters.AddWithValue(
                "@OldAuthor", oldMB.Author);
            updateCommand.Parameters.AddWithValue(
                "@OldISBNNumber", oldMB.ISBNNumber);
            updateCommand.Parameters.AddWithValue(
                "@OldDescription", oldMB.Description);
            updateCommand.Parameters.AddWithValue(
                "@OldCondition", oldMB.Condition);
            updateCommand.Parameters.AddWithValue(
                "@OldMemberID", oldMB.Member.MemberID);
            updateCommand.Parameters.AddWithValue(
                "@OldPrice", oldMB.Price);
            try
            {
                connection.Open();
                int count = updateCommand.ExecuteNonQuery();
                if (count > 0)
                    return true;
                else
                    return false;
            }
            catch (SqlException ex)
            {
                throw ex;
            }
            finally
            {
                connection.Close();
            }

Open in new window

And the code in my form
public MemberBook mb = new MemberBook();
        private void btnEdit_Click(object sender, EventArgs e)
        { 
            if (listView1.SelectedItems.Count > 0)
            {
                MemberBook newMB = new MemberBook();
                ListViewItem item = listView1.SelectedItems[0];
                mb.Member.MemberID = Convert.ToInt32(item.SubItems[1].Text);  
                mb.ISBNNumber = item.SubItems[2].Text;
                mb.Title = item.SubItems[3].Text;
                mb.Author = item.SubItems[4].Text;                        
                mb.Description = item.SubItems[5].Text;
                mb.Condition = item.SubItems[6].Text;
                mb.Price = Convert.ToDecimal(item.SubItems[7].Text);
                frmNewItem editFrm = new frmNewItem(mb);
                editFrm.GetNewMemberBook(mb);
                MemberBookInventoryDB.UpdateMemberBook(mb, newMB);
                LoadDataInListView();
            }
        }

Open in new window

I am going to assume that your ID is a unique Identifier, and if that is the case then the following code should work for you.

I am also assuming that "MMABooksDB.GetConnection()" sets your connection properties correctly.
public bool UpdateMemberBook(MemberBook newMB)
        {
            bool result = false;
            using(SqlConnection connection = MMABooksDB.GetConnection())
            {
                string updateStatement =
                    "UPDATE MemberBookInventory SET " +
                    "Title = @NewTitle, " +
                    "Author = @NewAuthor, " +
                    "ISBNNumber = @NewISBNNumber, " +
                    "Description= @NewDescription, " +
                    "Condition= @NewCondition, " +
                    "Price = @NewPrice, " +
                    "WHERE MemberID = @NewMemberID";
                using (SqlCommand updateCommand = new SqlCommand(updateStatement, connection))
                {
                    try
                    {
                        connection.Open();
                        updateCommand.Parameters.AddWithValue("@NewTitle", newMB.Title);
                        updateCommand.Parameters.AddWithValue("@NewAuthor", newMB.Author);
                        updateCommand.Parameters.AddWithValue("@NewISBNNumber", newMB.ISBNNumber);
                        updateCommand.Parameters.AddWithValue("@NewDescription", newMB.Description);
                        updateCommand.Parameters.AddWithValue("@NewCondition", newMB.Condition);
                        updateCommand.Parameters.AddWithValue("@NewMemberID", newMB.Member.MemberID);
                        updateCommand.Parameters.AddWithValue("@NewPrice", newMB.Price);
                        updateCommand.ExecuteNonQuery();
                        result = true;
                    }
                    catch (SqlException ex)
                    {
                        result = false;
                    }
                }
            }
            return result;
        }
    }

Open in new window

Well i would assume the code works I debugged and when the edit button is pressed it loads my memberbook info but when the sql statements executes everything return is null
Screen-shot-2011-04-07-at-10.48..png
This command will only return a true if there is no error running the command, or a false if there is an error.

you need to make the following change as well:

I am assuming that
editFrm.GetNewMemberBook(mb) updates the public object mb with the new details and sets the dialogresult to OK when the user clicks on the save button.

If this does not work can you please post the entire editFrm.cs code for me to check and then I will give you the code to get the item for the listview, edit the item in your form, and update it in SQL.

I'll need the class declaration for your MemberBook  class as well.
public MemberBook mb = new MemberBook();
        private void btnEdit_Click(object sender, EventArgs e)
        { 
            if (listView1.SelectedItems.Count > 0)
            {
                MemberBook newMB = new MemberBook();
                ListViewItem item = listView1.SelectedItems[0];
                mb.Member.MemberID = Convert.ToInt32(item.SubItems[1].Text);  
                mb.ISBNNumber = item.SubItems[2].Text;
                mb.Title = item.SubItems[3].Text;
                mb.Author = item.SubItems[4].Text;                        
                mb.Description = item.SubItems[5].Text;
                mb.Condition = item.SubItems[6].Text;
                mb.Price = Convert.ToDecimal(item.SubItems[7].Text);
                frmNewItem editFrm = new frmNewItem(mb);
                editFrm.GetNewMemberBook(mb);
                if(editFrm.DialogResult == DialogResult.OK)
                {
                    if(MemberBookInventoryDB.UpdateMemberBook(mb))       
                        LoadDataInListView();
                }
            }
        }

Open in new window

Ok. heres my new item class.. You can ignore all the putbook data, thats for populating and such I have no fully optimized the code so its kinda crazy sorry. the btn save works 2 ways, I have a bool on the parent form if add memberbook is clicked it allows me to make a new memberbook and add it to the DB. It has the else statement that works as my edit memberbook for this scenario. My memberbook class inherits from 2 classes but I will include the code. Feel free to mention if you see something you dont like or change I'm still learning =) But thank you for your time and patience this means alot


public partial class frmNewItem : Form
    {
        public MemberBook mb = new MemberBook();
        public Book b = new Book();
        public bool addMemberBook;

        public frmNewItem(MemberBook mb)
        {
            InitializeComponent();
            this.Text = String.Format("Book Info for ISBN {0}", mb.ISBNNumber);
            //these get populated no matter if editing or adding memberbook
            txtISBNNumber.Text = mb.ISBNNumber;
            txtAuthor.Text = mb.Author;
            txtTitle.Text = mb.Title;
            txtDescription.Text = mb.Description;
            //If add memberBook makes all the items that user enters to blank else populates 
            //for the edit form
            //txtMemberID.Text = mb.Member.MemberID.ToString();
            //txtCondition.Text = mb.Condition;
            // txtPrice.Text = mb.Price.ToString();

            //if (!addMemberBook)
            //{
            //    txtMemberID.Text = mb.Member.MemberID.ToString();
            //    txtCondition.Text = mb.Condition;
            //    txtPrice.Text = mb.Price.ToString();
            //}

        }

        private void frmNewItem_Load(object sender, EventArgs e)
        {
            if (txtAuthor.Text == "")
            {
                MemberBook mb = BookSearch.RetrieveFromISBN(txtISBNNumber.Text);              
                PutBookData(mb);
                if (!addMemberBook)
                {
                    txtMemberID.Text = mb.Member.MemberID.ToString();
                    txtCondition.Text = mb.Condition;
                    txtPrice.Text = mb.Price.ToString();
                }
                if (txtTitle.Text == "" && txtAuthor.Text == "")
                    MessageBox.Show("Could not populate book, please enter the book manaually");
            }         
        }

        //to populate  edit form
        public MemberBook GetNewMemberBook(MemberBook mb)
        {
            this.ShowDialog();
            txtAuthor.Text = mb.Author;
            txtISBNNumber.Text = mb.ISBNNumber;
            txtTitle.Text = mb.Title;
            txtDescription.Text = mb.Description;
            txtCondition.Text = mb.Condition;
            txtPrice.Text = mb.Price.ToString();
            return mb;

        }
        private bool IsValidData()
        {
            return Validator.IsPresent(txtTitle) &&
              Validator.IsPresent(txtAuthor) &&
              Validator.IsPresent(txtISBNNumber) &&
              Validator.IsPresent(txtDescription) &&
              Validator.IsPresent(txtCondition) &&
              Validator.IsPresent(txtPrice) &&
              Validator.IsDecimal(txtPrice);
        }

        //makes the memberbook data.
        private void PutMemberBookData(MemberBook memberBook)
        {
            mb.Member.MemberID = Convert.ToInt32(txtMemberID.Text);
            mb.Title = txtTitle.Text;
            mb.Author = txtAuthor.Text;
            mb.ISBNNumber = txtISBNNumber.Text;
            mb.Condition = txtCondition.Text;
            mb.Description = txtDescription.Text;
            mb.Price = Convert.ToDecimal(txtPrice.Text);
        }

        private void btnCancel_Click(object sender, EventArgs e)
        {
            this.Close();
        }
        private void btnSave_Click(object sender, EventArgs e)
        {
            if (IsValidData())
            {
                if (addMemberBook)
                {
                    mb = new MemberBook();
                    //this.PutBookData(b)
                    txtMemberID.Focus(); ;
                    this.PutMemberBookData(mb);                  
                    try
                    {
                        Book newBook = new Book();
                        PutBookCacheData(b);
                        // b.Title = txtTitle.Text;
                        //b.Author = txtAuthor.Text;
                        //b.Description = txtDescription.Text;
                        //b.ISBNNumber = txtISBNNumber.Text;

                        BookCacheDB.addOrUpdateBook(b);

                        mb.Member.MemberID = MemberBookInventoryDB.AddMemberBook(mb);
                        this.DialogResult = DialogResult.OK;

                    }

                    catch (Exception ex)
                    {
                        MessageBox.Show(ex.Message, ex.GetType().ToString());
                    }

                }
                else
                {
                    try
                    {
                        MemberBook newMB = new MemberBook();
                        MemberBookInventoryDB.UpdateMemberBook(newMB);
                        this.DialogResult = DialogResult.OK;
                    }

                    catch (Exception ex)
                    {
                        MessageBox.Show(ex.Message, ex.GetType().ToString());
                    }
                }
            }
        }
          //for the scan ISBN 
        public void PutBookData(MemberBook mb)
        {
            // The form populates an isbn number and if that number is not foun
            //the form will not be populated therefore this is important to have.
            txtTitle.Text = mb.Title;
            txtAuthor.Text = mb.Author;
            txtDescription.Text = mb.Description;  
            if (mb.Author == null)
            {   
                MessageBox.Show("Could not populate book, please enter the book manaually");
            }
   
        }
        //for the bookcache
        public void PutBookCacheData(Book b)
        {
            b.Title = txtTitle.Text;
            b.Author = txtAuthor.Text;
            b.Description = txtDescription.Text;
            b.ISBNNumber = txtISBNNumber.Text;

        }   
    }
}
   public class MemberBook : Book

    {
        private int bookID;
        private Member member { get; set; }

        public MemberBook() 
        {
            this.Member = new Member();
            Member = member;
        }
       
        public MemberBook(String bookId, string title, string author, string iSBNNumber, string condition,string description, decimal price) 
            : base (title, author, iSBNNumber, condition, description, price)
        {
            this.BookID = bookID;
            this.Member = new Member();
            Member = member;
        }

        public int BookID
        {
            get
            {
                return bookID;
            }
            set
            {
                bookID = value;
            }
        }

        public Member Member
        {
            get
            {
                return member;
            }
            set
            {
                member = value;
            }
        }
    
    }
}

Open in new window

I have put all my comments in with this:

//**

So that you can see my comments

Because you are saving the data from inside the form (I'm assuming the MemberBookInventoryDB class does the saving), it is not necessary to do this from the caller of the form anymore.

So the only thing you need to do from the caller is to check for the dialogResult.OK, and refresh your listview if that is the case. See my btnEdit_Click snippet . I hope this helps you.

public MemberBook mb = new MemberBook();
        private void btnEdit_Click(object sender, EventArgs e)
        { 
            if (listView1.SelectedItems.Count > 0)
            {
                MemberBook newMB = new MemberBook();
                ListViewItem item = listView1.SelectedItems[0];
                mb.Member.MemberID = Convert.ToInt32(item.SubItems[1].Text);  
                mb.ISBNNumber = item.SubItems[2].Text;
                mb.Title = item.SubItems[3].Text;
                mb.Author = item.SubItems[4].Text;                        
                mb.Description = item.SubItems[5].Text;
                mb.Condition = item.SubItems[6].Text;
                mb.Price = Convert.ToDecimal(item.SubItems[7].Text);
                frmNewItem editFrm = new frmNewItem(mb);
                editFrm.GetNewMemberBook(mb);
                if(editFrm.DialogResult == DialogResult.OK)     
                   LoadDataInListView();                
             }
        }

Open in new window

public partial class frmNewItem : Form
    {
        public MemberBook mb = new MemberBook();
        public Book b = new Book();
        public bool addMemberBook;

        public frmNewItem(MemberBook mb)
        {
            InitializeComponent();
            this.Text = String.Format("Book Info for ISBN {0}", mb.ISBNNumber);
            //these get populated no matter if editing or adding memberbook
            txtISBNNumber.Text = mb.ISBNNumber;
            txtAuthor.Text = mb.Author;
            txtTitle.Text = mb.Title;
            txtDescription.Text = mb.Description;
            //If add memberBook makes all the items that user enters to blank else populates 
            //for the edit form
            //txtMemberID.Text = mb.Member.MemberID.ToString();
            //txtCondition.Text = mb.Condition;
            // txtPrice.Text = mb.Price.ToString();

            //if (!addMemberBook)
            //{
            //    txtMemberID.Text = mb.Member.MemberID.ToString();
            //    txtCondition.Text = mb.Condition;
            //    txtPrice.Text = mb.Price.ToString();
            //}

        }

        private void frmNewItem_Load(object sender, EventArgs e)
        {
            if (txtAuthor.Text == "")
            {
                MemberBook mb = BookSearch.RetrieveFromISBN(txtISBNNumber.Text);
                PutBookData(mb);
                if (!addMemberBook)
                {
                    txtMemberID.Text = mb.Member.MemberID.ToString();
                    txtCondition.Text = mb.Condition;
                    txtPrice.Text = mb.Price.ToString();
                }
                if (txtTitle.Text == "" && txtAuthor.Text == "")
                    MessageBox.Show("Could not populate book, please enter the book manaually");
            }
        }

        //to populate  edit form
        public MemberBook GetNewMemberBook(MemberBook mb)
        {
            //** I'm not sure why you have this here, so I'm removing it
            //** you can put it back if there is a good reason to have it here
            //**this.ShowDialog();
            txtAuthor.Text = mb.Author;
            txtISBNNumber.Text = mb.ISBNNumber;
            txtTitle.Text = mb.Title;
            txtDescription.Text = mb.Description;
            txtCondition.Text = mb.Condition;
            txtPrice.Text = mb.Price.ToString();
            return mb;

        }
        private bool IsValidData()
        {
            return Validator.IsPresent(txtTitle) &&
              Validator.IsPresent(txtAuthor) &&
              Validator.IsPresent(txtISBNNumber) &&
              Validator.IsPresent(txtDescription) &&
              Validator.IsPresent(txtCondition) &&
              Validator.IsPresent(txtPrice) &&
              Validator.IsDecimal(txtPrice);
        }

        //makes the memberbook data.
        //**I don't see why you are passing a MemberBook instance here, so take this out
        //**private void PutMemberBookData(MemberBook memberBook)
        private void PutMemberBookData()
        {
            mb.Member.MemberID = Convert.ToInt32(txtMemberID.Text);
            mb.Title = txtTitle.Text;
            mb.Author = txtAuthor.Text;
            mb.ISBNNumber = txtISBNNumber.Text;
            mb.Condition = txtCondition.Text;
            mb.Description = txtDescription.Text;
            mb.Price = Convert.ToDecimal(txtPrice.Text);
        }

        private void btnCancel_Click(object sender, EventArgs e)
        {
            this.Close();
        }
        private void btnSave_Click(object sender, EventArgs e)
        {
            if (IsValidData())
            {
                //** put the try here rather to avoid code duplication
                try
                {
                    if (addMemberBook)
                    {
                        //**You have already created this instance when you declared it, so take this out
                        //**mb = new MemberBook();
                        //this.PutBookData(b)
                        txtMemberID.Focus();
                        //**No need to pass the memberbook, because it is available from being declared at the top of this form
                        //this.PutMemberBookData(mb);                  
                        PutMemberBookData();
                        Book newBook = new Book();
                        PutBookCacheData(b);
                        // b.Title = txtTitle.Text;
                        //b.Author = txtAuthor.Text;
                        //b.Description = txtDescription.Text;
                        //b.ISBNNumber = txtISBNNumber.Text;

                        BookCacheDB.addOrUpdateBook(b);

                        mb.Member.MemberID = MemberBookInventoryDB.AddMemberBook(mb);
                        //**Put this at the end to avoid code duplication
                        //this.DialogResult = DialogResult.OK;


                    }
                    else
                    {
                        MemberBook newMB = new MemberBook();
                        MemberBookInventoryDB.UpdateMemberBook(newMB);
                        //** Put this at the end to avoid code duplication
                        //this.DialogResult = DialogResult.OK;
                    }
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.Message, ex.GetType().ToString());
                }
                //** put the dialog result and the close here
                this.DialogResult = DialogResult.OK;
                this.Close();
            }
        }
        //for the scan ISBN 
        public void PutBookData(MemberBook mb)
        {
            // The form populates an isbn number and if that number is not foun
            //the form will not be populated therefore this is important to have.
            txtTitle.Text = mb.Title;
            txtAuthor.Text = mb.Author;
            txtDescription.Text = mb.Description;
            if (mb.Author == null)
            {
                MessageBox.Show("Could not populate book, please enter the book manaually");
            }

        }
        //for the bookcache
        public void PutBookCacheData(Book b)
        {
            b.Title = txtTitle.Text;
            b.Author = txtAuthor.Text;
            b.Description = txtDescription.Text;
            b.ISBNNumber = txtISBNNumber.Text;

        }
    }

Open in new window

Thanks for the helpful code, when debugging the sql statement you posted perviously along with the edited new item  form  newmb is still returning null.. any ideas to fix this?
Sorry linkCube1, I missed that one.


I have changed the code to call the PutMemberBookData() method directly after validating the code, so that we only have to do it once. You can then use that insance of mb for either the add or the update.

I hope we have cracked it now.

Regards,

Mike



else
                    {
                        //** this is not necessary, because you have set all the properties in mb
                        //**MemberBook newMB = new MemberBook();
                       //** Do the update using mb
                        PutMemberBookData();
                        MemberBookInventoryDB.UpdateMemberBook(mb);
                        //** Put this at the end to avoid code duplication
                        //this.DialogResult = DialogResult.OK;
                    }

public partial class frmNewItem : Form
    {
        public MemberBook mb = new MemberBook();
        public Book b = new Book();
        public bool addMemberBook;

        public frmNewItem(MemberBook mb)
        {
            InitializeComponent();
            this.Text = String.Format("Book Info for ISBN {0}", mb.ISBNNumber);
            //these get populated no matter if editing or adding memberbook
            txtISBNNumber.Text = mb.ISBNNumber;
            txtAuthor.Text = mb.Author;
            txtTitle.Text = mb.Title;
            txtDescription.Text = mb.Description;
            //If add memberBook makes all the items that user enters to blank else populates 
            //for the edit form
            //txtMemberID.Text = mb.Member.MemberID.ToString();
            //txtCondition.Text = mb.Condition;
            // txtPrice.Text = mb.Price.ToString();

            //if (!addMemberBook)
            //{
            //    txtMemberID.Text = mb.Member.MemberID.ToString();
            //    txtCondition.Text = mb.Condition;
            //    txtPrice.Text = mb.Price.ToString();
            //}

        }

        private void frmNewItem_Load(object sender, EventArgs e)
        {
            if (txtAuthor.Text == "")
            {
                MemberBook mb = BookSearch.RetrieveFromISBN(txtISBNNumber.Text);
                PutBookData(mb);
                if (!addMemberBook)
                {
                    txtMemberID.Text = mb.Member.MemberID.ToString();
                    txtCondition.Text = mb.Condition;
                    txtPrice.Text = mb.Price.ToString();
                }
                if (txtTitle.Text == "" && txtAuthor.Text == "")
                    MessageBox.Show("Could not populate book, please enter the book manaually");
            }
        }

        //to populate  edit form
        public MemberBook GetNewMemberBook(MemberBook mb)
        {
            //** I'm not sure why you have this here, so I'm removing it
            //** you can put it back if there is a good reason to have it here
            //**this.ShowDialog();
            txtAuthor.Text = mb.Author;
            txtISBNNumber.Text = mb.ISBNNumber;
            txtTitle.Text = mb.Title;
            txtDescription.Text = mb.Description;
            txtCondition.Text = mb.Condition;
            txtPrice.Text = mb.Price.ToString();
            return mb;

        }
        private bool IsValidData()
        {
            return Validator.IsPresent(txtTitle) &&
              Validator.IsPresent(txtAuthor) &&
              Validator.IsPresent(txtISBNNumber) &&
              Validator.IsPresent(txtDescription) &&
              Validator.IsPresent(txtCondition) &&
              Validator.IsPresent(txtPrice) &&
              Validator.IsDecimal(txtPrice);
        }

        //makes the memberbook data.
        //**I don't see why you are passing a MemberBook instance here, so take this out
        //**private void PutMemberBookData(MemberBook memberBook)
        private void PutMemberBookData()
        {
            mb.Member.MemberID = Convert.ToInt32(txtMemberID.Text);
            mb.Title = txtTitle.Text;
            mb.Author = txtAuthor.Text;
            mb.ISBNNumber = txtISBNNumber.Text;
            mb.Condition = txtCondition.Text;
            mb.Description = txtDescription.Text;
            mb.Price = Convert.ToDecimal(txtPrice.Text);
        }

        private void btnCancel_Click(object sender, EventArgs e)
        {
            this.Close();
        }
        private void btnSave_Click(object sender, EventArgs e)
        {
            if (IsValidData())
            {
                //** put the try here rather to avoid code duplication
                try
                {
                    //** Put this line here to avoid code duplication
                    PutMemberBookData();  //** this sets the mb value to your validated form data
                    if (addMemberBook)
                    {
                        //**You have already created this instance when you declared it, so take this out
                        //**mb = new MemberBook();
                        //this.PutBookData(b)
                        txtMemberID.Focus();
                        //**No need to pass the memberbook, because it is available from being declared at the top of this form
                        //this.PutMemberBookData(mb);
                        //** take this out and do it as the first line after you have validated your data
                        //**PutMemberBookData();
                        Book newBook = new Book();
                        PutBookCacheData(b);
                        // b.Title = txtTitle.Text;
                        //b.Author = txtAuthor.Text;
                        //b.Description = txtDescription.Text;
                        //b.ISBNNumber = txtISBNNumber.Text;

                        BookCacheDB.addOrUpdateBook(b);

                        mb.Member.MemberID = MemberBookInventoryDB.AddMemberBook(mb);
                        //**Put this at the end to avoid code duplication
                        //this.DialogResult = DialogResult.OK;


                    }
                    else
                    {
                        //**There is no need to create a new instance of the member book, because we can use the mb instance that we have already updated in the first line after validation
                        //**MemberBook newMB = new MemberBook();
                        //** Here we call your update method, and pass it the mb instance.
                        //**MemberBookInventoryDB.UpdateMemberBook(newMB);
                        MemberBookInventoryDB.UpdateMemberBook(mb);
                        //** Put this at the end to avoid code duplication
                        //this.DialogResult = DialogResult.OK;
                    }
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.Message, ex.GetType().ToString());
                }
                //** put the dialog result and the close here
                this.DialogResult = DialogResult.OK;
                this.Close();
            }
        }
        //for the scan ISBN 
        public void PutBookData(MemberBook mb)
        {
            // The form populates an isbn number and if that number is not foun
            //the form will not be populated therefore this is important to have.
            txtTitle.Text = mb.Title;
            txtAuthor.Text = mb.Author;
            txtDescription.Text = mb.Description;
            if (mb.Author == null)
            {
                MessageBox.Show("Could not populate book, please enter the book manaually");
            }

        }
        //for the bookcache
        public void PutBookCacheData(Book b)
        {
            b.Title = txtTitle.Text;
            b.Author = txtAuthor.Text;
            b.Description = txtDescription.Text;
            b.ISBNNumber = txtISBNNumber.Text;

        }
    }

Open in new window

Oops, ignore the first 11 lines, i was supposed to delete them before posting.
it seems to returns false still. looks like its assigning properly but im not sure if the update statement is working
Your command statement has an extra comma in it which needs to be removed

string updateStatement =
                    "UPDATE MemberBookInventory SET " +
                    "Title = @NewTitle, " +
                    "Author = @NewAuthor, " +
                    "ISBNNumber = @NewISBNNumber, " +
                    "Description= @NewDescription, " +
                    "Condition= @NewCondition, " +
                     "Price = @NewPrice " + //"Price = @NewPrice, " +
                    "WHERE MemberID = @NewMemberID";
ok works now, but how do i update it so that it only updates 1 where memberID = memberID and bookID = bookID
ASKER CERTIFIED SOLUTION
Avatar of mkobrin
mkobrin

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Works thanks alot for your time!
No problem,

All the best with your learning.