简体   繁体   中英

moving object from listbox to another listbox in C# winform

How i can moving object( that is include name and id) from listbox to another listbox and save it? i wrote this:

 if (lstActivity.SelectedIndex != -1)
            {

                int intSelectedIndex = lstActivity.SelectedIndex;
                if (intSelectedIndex >= 0)
                {

 listbox.Items.Add(((Parking_Services.Activity)lstActivity.SelectedItem).ActivityName);

                    lstActivity.Items.RemoveAt(intSelectedIndex);
                }
            }

it is worked but when i want save this (after clicked button), it get exception : " can not cast syste.string to (Parking_Services.Activity)."

  private void btnSave_Click(object sender, EventArgs e)
        {
            int intActivityID;
            Parking_Services.Service1 ii = new Parking_Services.Service1();
            for (int i = 0; i <= listbox.Items.Count; i++)                                            //save item from listbox is wrong
            {
                intActivityID = ((Parking_Services.Activity)listbox.Items[i]).ActivityID;
                string strMessage = ii.AllowUserActivityByType(intUserTypeID, intActivityID, FrmLogin.intUserId);

            }

This is because you're not adding an object of type Parking_Services.Activity to the list box, but the ActivityName of the selected Parking_Services.Activity in the following line:

listbox.Items.Add(((Parking_Services.Activity)lstActivity.SelectedItem).ActivityName);

I'd expect this to be a string. Instead you may try this:

listbox.Items.Add(lstActivity.SelectedItem);

Given that the item in lstActivity is of type Parking_Services.Activity .

The line...

intActivityID = ((Parking_Services.Activity)listbox.Items[i]).ActivityID;

...fails, because the items in listbox are String s and not Parking_Services.Activity s. And they are String s because, you add String s in the line...

listbox.Items.Add(((Parking_Services.Activity)lstActivity.SelectedItem).ActivityName);

I suppose the ActivityName property is a String . So there is a design error in either of those two lines.


I suggest the following fix: Add the whole Parking_Services.Activity objects to listbox ...

listbox.Items.Add((Parking_Services.Activity)lstActivity.SelectedItem);

...and override ToString() in the Parking_Services.Activity class, so listbox displays them correctly:

public class Activity
{
    ...

    public override string ToString()
    {
        return ActivityName;
    }
}

A ListBox always calls ToString() on the object s passed to it, when painting their list entries. So, by overriding ToString() , you can control how your Parking_Services.Activity s are displayed.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM