none
Accessing an array from another class in c#

    Question

  • Hi,

    I'm new to programming and I've been working with c# for a few weeks now and I'm curious as to how I would access an array I have in one class with another class.

    Here's an example:

    I have a listbox that lists the type,date,length, and distance of an exercise. When they select a line in the listbox it should add the details of that line into the text boxes above. They can then edit something in one of those text boxes and click the Modify button to change it in the list box.

    Here is the class that the array is in.

        private string deserialize(string line)
        {
            string[] info = line.Split('\t');
    
            string type = info[0];
            string date = info[1];
            string time = info[2];
            string distance = info[3];
    
            return (type.PadLeft(5) + "                                         " + date 
                + "                                             " + time 
                + "                                                     " + distance.PadRight(5));
            
        }

    I want to access my array in the exerciseListBox_SelectedIndexChanged event as shown below:

        private void exerciseListBox_SelectedIndexChanged(object sender, EventArgs e)
        {
            
        }

    If it matters at all I am writing this data into a text file and then reading it back.

    If there is more part of my code that is needed then just let me know. Thanks for any help that you guys can give.

    Mark

    Monday, February 11, 2013 1:19 AM

Answers

  • Hi,

    Please check the below code,

    namespace WindowsFormsApplication2
    {
        public partial class Form2 : Form
        {
            List<string> mylist = new List<string>();
            int currentIndex = -1;
            public Form2()
            {
                InitializeComponent();
            }
    
          
    
            private void btnSum_Click(object sender, EventArgs e)
            {
             
                //Inserting sample values into the list box
                exerciseListBox.Items.Add(deserialize(string.Format("{0}\t{1}\t{2}\t{3}","Type1","date1","Time1","Distance1")));
                exerciseListBox.Items.Add(deserialize(string.Format("{0}\t{1}\t{2}\t{3}", "Type2", "date2", "Time2", "Distance2")));
                exerciseListBox.Items.Add(deserialize(string.Format("{0}\t{1}\t{2}\t{3}", "Type3", "date3", "Time3", "Distance3")));
               
            }
    
            private string deserialize(string line)
            {
                string[] info = line.Split('\t');
    
                string type = info[0];
                string date = info[1];
                string time = info[2];
                string distance = info[3];
                string finalValue =type + "@"+ date + "@" + time + "@" + distance;
                mylist.Add(finalValue); //insert the value into global variable
                return (type.PadLeft(5) + "                                         " + date
                    + "                                             " + time
                    + "                                                     " + distance.PadRight(5));
    
    
    
            }
    
            private void exerciseListBox_SelectedIndexChanged(object sender, EventArgs e)
            {
                if (exerciseListBox.SelectedIndex !=-1)
                {
                    currentIndex = exerciseListBox.SelectedIndex; //Store the selected index;
    
                    string selected = mylist[exerciseListBox.SelectedIndex];
                    string [] info = selected.Split('@');
                    txtDate.Tag = info[0]; //storing the type
                    txtDate.Text = info[1];
                    txtTime.Text = info[2];
                    txtDistance.Text = info[3];
    
    
                }
            }
    
            private void btnModify_Click(object sender, EventArgs e)
            {
    
                if (currentIndex != -1)
                {
                    string type = txtDate.Tag.ToString();
                    string date = txtDate.Text;
                    string time = txtTime.Text;
                    string distance = txtDistance.Text;
                    string finalValue = date + "@" + time + "@" + distance;
    
                    mylist[currentIndex] = finalValue; //Change the global array
    
    
                    string modifiedText = type.PadLeft(5) + "                                         " + date
                        + "                                             " + time
                        + "                                                     " + distance.PadRight(5);
    
    
                    exerciseListBox.Items.RemoveAt(currentIndex);
                    exerciseListBox.Items.Insert(currentIndex, modifiedText);
                }
    
            }
            
         
        }
    
    }

    Best Regards

    Muthuraja

    Monday, February 11, 2013 4:15 AM

All replies

  • I usually prefer overriding an object's ToString() method and then passing that object as a value to ListBox.Items.Add(). Overriding the ToString() method enables you to control an object's string representation in a ListBox control whilst still allowing you to continue working with the actual object as a ListBox item.

    Monday, February 11, 2013 1:39 AM
  • I usually prefer overriding an object's ToString() method and then passing that object as a value to ListBox.Items.Add(). Overriding the ToString() method enables you to control an object's string representation in a ListBox control whilst still allowing you to continue working with the actual object as a ListBox item.

    Could you explain how you would do that? Like I said I am fairly new to programming and c# so the more detail the better
    Monday, February 11, 2013 2:32 AM
  • Can you give us what are going to do with your application? 


    Please consider my reply. Please mark it as helpful. :)

    Monday, February 11, 2013 3:16 AM
  • Firstly I define a custom data type:

    public class Exercise
    {
        public string type = "Not Set";
        public DateTime datetimeValue = DateTime.Now;
        public int distance = 0;
    
        public override string ToString()
        {
            string returnValue = type.PadRight(7) + "\t\t";
            returnValue += datetimeValue.ToString("yyyy/MM/dd HH:mm:ss") + "\t";
            returnValue += distance.ToString();
    
            return returnValue;
        }
    }

    Notice how I define the ToString() method indicating the override keyword. In C# all objects automatically inherit from the Object class, which defines a ToString() method. When defining a method in a derived type which has a similiar method signature as a method defined in a parent type you can specify the override keyword as part of the derived type's method signature. The override keyword ensures that the correct version of ToString() gets called, refer to the topic of upcasting.

    Next I create three instances of type Exercise and add as Listbox items:

    public Form1()
    {
        InitializeComponent();
    
        Exercise exc1 = new Exercise();
        exc1.distance = 100;
        exc1.type = "sprint";
    
        listBox1.Items.Add(exc1);
    
        Exercise exc2 = new Exercise();
        exc2.distance = 5;
        exc2.type = "long jump";
    
        listBox1.Items.Add(exc2);
    
        Exercise exc3 = new Exercise();
        exc3.distance = 10000;
        exc3.type = "marathon";
    
        listBox1.Items.Add(exc3);
    }

    The last code snippet illustrates retrieving the selected object from a Listbox when the user selects an item:

    private void listBox1_SelectedIndexChanged(object sender, EventArgs e)
    {
        if (listBox1.SelectedIndex != -1)
        {
            if (listBox1.SelectedItem is Exercise)
            {
                Exercise exc = (Exercise)listBox1.SelectedItem;
                MessageBox.Show(exc.ToString());
            }
        }
    }

    For some reason I'm being prevented from posting links, fix up the following text to get a link to download the sample source code:

    sdrv.ms / Y3N8nI

    Monday, February 11, 2013 3:50 AM
  • Can you give us what are going to do with your application? 


    Please consider my reply. Please mark it as helpful. :)

    For my assignment people enter in information about an exercise into four text boxes then and then they can add that information to a list box. When the select an item in the list box it will appear in the appropriate text boxes. You can then edit the information and hit the Modify button to change the information in the list box. There is also a clear and exit button. I am just having trouble with this modify button.
    Monday, February 11, 2013 3:56 AM
  • Hi,

    Please check the below code,

    namespace WindowsFormsApplication2
    {
        public partial class Form2 : Form
        {
            List<string> mylist = new List<string>();
            int currentIndex = -1;
            public Form2()
            {
                InitializeComponent();
            }
    
          
    
            private void btnSum_Click(object sender, EventArgs e)
            {
             
                //Inserting sample values into the list box
                exerciseListBox.Items.Add(deserialize(string.Format("{0}\t{1}\t{2}\t{3}","Type1","date1","Time1","Distance1")));
                exerciseListBox.Items.Add(deserialize(string.Format("{0}\t{1}\t{2}\t{3}", "Type2", "date2", "Time2", "Distance2")));
                exerciseListBox.Items.Add(deserialize(string.Format("{0}\t{1}\t{2}\t{3}", "Type3", "date3", "Time3", "Distance3")));
               
            }
    
            private string deserialize(string line)
            {
                string[] info = line.Split('\t');
    
                string type = info[0];
                string date = info[1];
                string time = info[2];
                string distance = info[3];
                string finalValue =type + "@"+ date + "@" + time + "@" + distance;
                mylist.Add(finalValue); //insert the value into global variable
                return (type.PadLeft(5) + "                                         " + date
                    + "                                             " + time
                    + "                                                     " + distance.PadRight(5));
    
    
    
            }
    
            private void exerciseListBox_SelectedIndexChanged(object sender, EventArgs e)
            {
                if (exerciseListBox.SelectedIndex !=-1)
                {
                    currentIndex = exerciseListBox.SelectedIndex; //Store the selected index;
    
                    string selected = mylist[exerciseListBox.SelectedIndex];
                    string [] info = selected.Split('@');
                    txtDate.Tag = info[0]; //storing the type
                    txtDate.Text = info[1];
                    txtTime.Text = info[2];
                    txtDistance.Text = info[3];
    
    
                }
            }
    
            private void btnModify_Click(object sender, EventArgs e)
            {
    
                if (currentIndex != -1)
                {
                    string type = txtDate.Tag.ToString();
                    string date = txtDate.Text;
                    string time = txtTime.Text;
                    string distance = txtDistance.Text;
                    string finalValue = date + "@" + time + "@" + distance;
    
                    mylist[currentIndex] = finalValue; //Change the global array
    
    
                    string modifiedText = type.PadLeft(5) + "                                         " + date
                        + "                                             " + time
                        + "                                                     " + distance.PadRight(5);
    
    
                    exerciseListBox.Items.RemoveAt(currentIndex);
                    exerciseListBox.Items.Insert(currentIndex, modifiedText);
                }
    
            }
            
         
        }
    
    }

    Best Regards

    Muthuraja

    Monday, February 11, 2013 4:15 AM