?
Solved

C# - Using a Class

Posted on 2005-03-22
6
Medium Priority
?
372 Views
Last Modified: 2010-04-17
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
Comment
Question by:Dys
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 3
  • 2
6 Comments
 
LVL 8

Expert Comment

by:AaronReams
ID: 13607820
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
 

Expert Comment

by:GaryLamJ
ID: 13608130
Hi Dys,

Yeah this always happened to me, you just need to remove the reference and add it again.
remember restart Visual Studio.
0
 

Author Comment

by:Dys
ID: 13608597
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
Efficient way to get backups off site to Azure

This user guide provides instructions on how to deploy and configure both a StoneFly Scale Out NAS Enterprise Cloud Drive virtual machine and Veeam Cloud Connect in the Microsoft Azure Cloud.

 
LVL 8

Accepted Solution

by:
AaronReams earned 500 total points
ID: 13614406
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
 

Author Comment

by:Dys
ID: 13614592
Excellent! That solved the problem - points have been awarded. Thanks for picking up that error in the constructor.
0
 
LVL 8

Expert Comment

by:AaronReams
ID: 13614605
No problem.  Glad I could help. -Aåron
0

Featured Post

[Webinar] Lessons on Recovering from Petya

Skyport is working hard to help customers recover from recent attacks, like the Petya worm. This work has brought to light some important lessons. New malware attacks like this can take down your entire environment. Learn from others mistakes on how to prevent Petya like worms.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Uncontrolled local administrators groups within any organization pose a huge security risk. Because these groups are locally managed it becomes difficult to audit and maintain them.
Compliance and data security require steps be taken to prevent unauthorized users from copying data.  Here's one method to prevent data theft via USB drives (and writable optical media).
This video shows how to use Hyena, from SystemTools Software, to bulk import 100 user accounts from an external text file. View in 1080p for best video quality.
This video shows how to use Hyena, from SystemTools Software, to update 100 user accounts from an external text file. View in 1080p for best video quality.
Suggested Courses

765 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question