• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 376
  • Last Modified:

C# - Using a Class

I'm new to C#, having programmed VB6 and VB.NET for while. I have a small app with a combo box that I want to populate with the names of some cities and delivery prices to those cities. I've created a cCity class in my C# project with two properties - name, deliveryprice. What I want to do now is add instances of the cCity class to the combo box. The code I've used in VB.NET is this:

cboCities.Items.Add(New cCity("New York", 11.65))

When I try this in C# (using lower case new), cCity does not show up in intellisense as an available class, eventhough it is part of my project.

What am I doing wrong? Help...
0
Dys
Asked:
Dys
  • 3
  • 2
1 Solution
 
AaronReamsCommented:
Hi Dys,

I order to do what you're trying to do you'll need to use databinding.  Databinding basically associates a list with the combobox.  Whenever you modify the list the combobox is updated.  The next thing you need to know is that if you want to return a custom string from an object you add the list, you need to override ToString().

Note: if cCity is not showing up in intellisense, you probably have it defined in a different workspace.

I'll post a working example of a sample solution for you... Cheers -A.R.


==================================================

using System;
using System.Drawing;
using System.Collections;
using System.ComponentModel;
using System.Windows.Forms;
using System.Data;

namespace WindowsApplication6
{
      /// <summary>
      /// Summary description for Form1.
      /// </summary>
      public class Form1 : System.Windows.Forms.Form
      {
            private System.Windows.Forms.ComboBox comboBox1;
            /// <summary>
            /// Required designer variable.
            /// </summary>
            private System.ComponentModel.Container components = null;
            public ArrayList list = new ArrayList();

            public Form1()
            {
                  //
                  // Required for Windows Form Designer support
                  //
                  InitializeComponent();

                  //
                  // TODO: Add any constructor code after InitializeComponent call
                  //
            }

            /// <summary>
            /// Clean up any resources being used.
            /// </summary>
            protected override void Dispose( bool disposing )
            {
                  if( disposing )
                  {
                        if (components != null)
                        {
                              components.Dispose();
                        }
                  }
                  base.Dispose( disposing );
            }

            #region Windows Form Designer generated code
            /// <summary>
            /// Required method for Designer support - do not modify
            /// the contents of this method with the code editor.
            /// </summary>
            private void InitializeComponent()
            {
                  this.comboBox1 = new System.Windows.Forms.ComboBox();
                  this.SuspendLayout();
                  //
                  // comboBox1
                  //
                  this.comboBox1.Location = new System.Drawing.Point(32, 56);
                  this.comboBox1.Name = "comboBox1";
                  this.comboBox1.Size = new System.Drawing.Size(176, 21);
                  this.comboBox1.TabIndex = 0;
                  this.comboBox1.Text = "comboBox1";
                  this.comboBox1.SelectedIndexChanged += new System.EventHandler(this.comboBox1_SelectedIndexChanged);
                  //
                  // Form1
                  //
                  this.AutoScaleBaseSize = new System.Drawing.Size(5, 13);
                  this.ClientSize = new System.Drawing.Size(292, 266);
                  this.Controls.Add(this.comboBox1);
                  this.Name = "Form1";
                  this.Text = "Form1";
                  this.Load += new System.EventHandler(this.Form1_Load);
                  this.ResumeLayout(false);

            }
            #endregion

            /// <summary>
            /// The main entry point for the application.
            /// </summary>
            [STAThread]
            static void Main()
            {
                  Application.Run(new Form1());
            }

            private void comboBox1_SelectedIndexChanged(object sender, System.EventArgs e)
            {
            
            }

            private void Form1_Load(object sender, System.EventArgs e)
            {

                  list.Add("First Entry");
                  list.Add(new cCity("New York",11.65));
                  list.Add("Third Entry");
                  comboBox1.DataSource=list;
            }
      }

      public class cCity
      {
            public string name = "";
            public double price = 0;
            public cCity(string n, double p)
            {
                  name=n;
                  price=p;
            }
            public override string ToString()
            {
                  return name+" "+price.ToString();
            }
      }
}
0
 
GaryLamJCommented:
Hi Dys,

Yeah this always happened to me, you just need to remove the reference and add it again.
remember restart Visual Studio.
0
 
DysAuthor Commented:
For GaryLam:
Thanks for the suggestions, but I tried it and it didn't work. Here's the procedure I followed. Right click on the cCity.cs class file in Project Explorer. Click on Exclude from Project. Then I shut down VS.NET and re-started. Again, right clicked on cCity.cs and selected include in Project. The process still didn't make it available with intellisense. But part of AaronReams suggestion worked to make it available in intellisense (read below).

For AaronReams:

Thanks to the quick response. Instead of having a separate file for my class (cCity.cs), I used your idea and included the class code at the bottom of my code window for the form. This then makes "cCity" available in intellisense - go figure. However, I'm not sure why I'd have to create an array list of items since C# already hasthe tools to do this in the combbnox control. The combobox "items" collection has an "Add" method. With cCity class now available in intellisense, I can write the following line of code:

cboCities.Items.Add(new cCity("New York", 11.65));

without any design time errors showing up. But when I run the code I get a runtime as follows:

An unhandled exception of type 'System.NullReferenceException' occurred in system.windows.forms.dll
Additional information: Object reference not set to an instance of an object.

So my problem is half solved. Any ideas on setting an instance. My form load code is like yours:

         private void Form1_Load(object sender, System.EventArgs e)
          {
                cboCities.Items.Add(new cCity("New York",11.65));
                // other cities would be added here
            }

And my cCity class code is as follows:

      public class cCity
      {
            private string m_name;
            private double m_delprice;

            public cCity(string cityname, double deliveryprice)
            {
                  m_name = name;
                  m_delprice = delprice;
            }

            public override string ToString()
            {
                  return m_name;
            }             

            public string name
            {
                  get
                  {
                        return m_name;
                  }
                  set
                  {
                        m_name = value;
                  }
            }

            public double delprice
            {
                  get
                  {
                        return m_delprice;
                  }
                  set
                  {
                        m_delprice = value;
                  }
            }

      }

So. I still need some help to setting the cCity objects. and if anyone out there can solve the class reference probject that would be great too.
0
Industry Leaders: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

 
AaronReamsCommented:
Sorry, you're right.  You don't have to use DataBinding if you don't want to... I'm just so used to using that with databases.

So in my original code in the load function delete everything else and just add...

                  comboBox1.Items.Add(new cCity("New York",11.65));

and it will work.

I think you're problem is in the constructor.

          public cCity(string cityname, double deliveryprice)
          {
               m_name = name;


i think you want m_name = cityname;

good luck -A.R.
0
 
DysAuthor Commented:
Excellent! That solved the problem - points have been awarded. Thanks for picking up that error in the constructor.
0
 
AaronReamsCommented:
No problem.  Glad I could help. -AĆ„ron
0

Featured Post

Keep up with what's happening at Experts Exchange!

Sign up to receive Decoded, a new monthly digest with product updates, feature release info, continuing education opportunities, and more.

  • 3
  • 2
Tackle projects and never again get stuck behind a technical roadblock.
Join Now