Solved

create a class that will lopad values to a combobox or a datagrid

Posted on 2014-10-09
8
115 Views
Last Modified: 2014-10-13
C# 2005 Professional

earning how to write classes


I want to write a class like i would do with a function in VB.net to load values to object that I place on my form

thank you
0
Comment
Question by:mphillip85
  • 5
  • 3
8 Comments
 
LVL 32

Expert Comment

by:it_saige
ID: 40371591
Creating a class that is used as a datasource is not that difficult.  It really just depend on the control you want to use to display the data.

For Example:
using System;

namespace CSharpExample
{
	/// <summary>Class Person.</summary>
	public class Person
	{
		/// <summary>The first name field</summary>
		private string fFirstName = string.Empty;
		/// <summary>The last name field</summary>
		private string fLastName = string.Empty;
		/// <summary>The birthday field</summary>
		private DateTime fBirthday = DateTime.MinValue;
		/// <summary>The gender field</summary>
		private Gender fGender = Gender.None;

		/// <summary>Gets or sets the first name.</summary>
		/// <value>The first name.</value>
		public string FirstName
		{
			get { return fFirstName; }
			set
			{
				if (!string.IsNullOrEmpty(value) && !value.Equals(fFirstName))
					fFirstName = value;
			}
		}

		/// <summary>Gets or sets the last name.</summary>
		/// <value>The last name.</value>
		public string LastName
		{
			get { return fLastName; }
			set
			{
				if (!string.IsNullOrEmpty(value) && !value.Equals(fLastName))
					fLastName = value;
			}
		}

		/// <summary>Gets or sets the birthday.</summary>
		/// <value>The birthday.</value>
		public DateTime Birthday
		{
			get { return fBirthday; }
			set
			{
				if (!value.Equals(fBirthday))
					fBirthday = value;
			}
		}

		/// <summary>Gets or sets the gender.</summary>
		/// <value>The gender.</value>
		public Gender Gender
		{
			get { return fGender; }
			set
			{
				if (!value.Equals(fGender))
					fGender = value;
			}
		}

		/// <summary>Initializes a new instance of the <see cref="Person"/> class.</summary>
		public Person() { ;}

		/// <summary>Initializes a new instance of the <see cref="Person"/> class.</summary>
		/// <param name="FirstName">The first name.</param>
		/// <param name="LastName">The last name.</param>
		public Person(string FirstName, string LastName) : this(FirstName, LastName, DateTime.MinValue, Gender.None) { ;}

		/// <summary>Initializes a new instance of the <see cref="Person"/> class.</summary>
		/// <param name="FirstName">The first name.</param>
		/// <param name="LastName">The last name.</param>
		/// <param name="Birthday">The birthday.</param>
		public Person(string FirstName, string LastName, DateTime Birthday) : this(FirstName, LastName, Birthday, Gender.None) { ;}

		/// <summary>Initializes a new instance of the <see cref="Person"/> class.</summary>
		/// <param name="FirstName">The first name.</param>
		/// <param name="LastName">The last name.</param>
		/// <param name="Birthday">The birthday.</param>
		/// <param name="Gender">The gender.</param>
		public Person(string FirstName, string LastName, DateTime Birthday, Gender Gender)
		{
			this.FirstName = FirstName;
			this.LastName = LastName;
			this.Birthday = Birthday;
			this.Gender = Gender;
		}

		/// <summary>Returns a <see cref="System.String" /> that represents this instance.</summary>
		/// <returns>A <see cref="System.String" /> that represents this instance.</returns>
		public override string ToString()
		{
			if (!string.IsNullOrEmpty(FirstName) && !string.IsNullOrEmpty(LastName))
				return string.Format("{0} {1}", FirstName, LastName);
			else
				return "Uninitialized Person";
		}
	}

	public enum Gender : int
	{
		None = 0,
		Male = 1,
		Female = 2,
		Declined = 3
	}
}

Open in new window


Now you could create a new List of people and put them into a datagrid or combobox (dont forget to add them to the form):
using System;
using System.Collections.Generic;
using System.Windows.Forms;

namespace CSharpExample
{
	public partial class Form1 : Form
	{
		private List<Person> People = new List<Person>() 
		{ 
			new Person("John", "Doe", DateTime.Now, Gender.Male), 
			new Person() 
			{ 
				FirstName = "Jane", 
				LastName = "Doe", 
				Birthday = DateTime.Parse("01/01/1989"), 
				Gender = Gender.Female 
			} 
		};

		public Form1()
		{
			InitializeComponent();
			People.Add(new Person("Bigfoot", "Henderson", Convert.ToDateTime("01/06/1961"), Gender.Declined));
		}

		private void Form1_Load(object sender, EventArgs e)
		{
			comboBox1.DataSource = People;
			dataGridView1.DataSource = People;
		}
	}
}

Open in new window


The above produces the following output:Both the Combobox and the DataGrid control are populated with our people.The drop down items.
-saige-
0
 

Author Comment

by:mphillip85
ID: 40371942
I just want to populate the properties of the combobox1 for example.

this is what the class would have in it.

with combobox1
.comboname = "combobox1"
.datasource  = "dataset1"
.displaymember = "columnname"
.valuemember  = "columnname"

end with

then in the main form i want to do this

namespace.program.loadcombo(string comboname, string dsource, string dmember, string vmember);

when I make this call in the main form load section it will pull the data from the database that I want.

then i can use the same code and modify it to use for the datagrid and filter off of the combobox selected value to trigger the rows to retrieve for the datagrid.

thank you
0
 

Author Comment

by:mphillip85
ID: 40371945
I would like to learn how to do this in a class rather than a function.
0
 
LVL 32

Accepted Solution

by:
it_saige earned 500 total points
ID: 40373042
Are you talking about something like this:

Extensions.cs -
using System.Windows.Forms;

namespace CSharpExample
{
	public static class Extensions
	{
		public static void Configure(this ComboBox Control, string ControlName, object DataSource, string DataMember = "", string ValueMember = "")
		{
			Control.Name = ControlName;
			Control.DataSource = DataSource;
			if (!string.IsNullOrEmpty(DataMember))
				Control.DisplayMember = DataMember;
			if (!string.IsNullOrEmpty(ValueMember))
				Control.ValueMember = ValueMember;
		}

		public static void Configure(this DataGridView Control, string ControlName, object DataSource, string DataMember = "")
		{
			Control.Name = ControlName;
			Control.DataSource = DataSource;
			if (!string.IsNullOrEmpty(DataMember))
				Control.DataMember = DataMember;
		}
	}
}

Open in new window

Form1.cs -
using System;
using System.Collections.Generic;
using System.Windows.Forms;

namespace CSharpExample
{
	public partial class Form1 : Form
	{
		private List<Person> People = new List<Person>() 
		{ 
			new Person("John", "Doe", DateTime.Now, Gender.Male), 
			new Person() 
			{ 
				FirstName = "Jane", 
				LastName = "Doe", 
				Birthday = DateTime.Parse("01/01/1989"), 
				Gender = Gender.Female 
			} 
		};

		public Form1()
		{
			InitializeComponent();
			People.Add(new Person("Bigfoot", "Henderson", Convert.ToDateTime("01/06/1961"), Gender.Declined));
		}

		private void Form1_Load(object sender, EventArgs e)
		{
			comboBox1.Configure("ComboBox1", People);
			dataGridView1.Configure("DataGridView1", People);
		}
	}
}

Open in new window


-saige-
0
Free Trending Threat Insights Every Day

Enhance your security with threat intelligence from the web. Get trending threat insights on hackers, exploits, and suspicious IP addresses delivered to your inbox with our free Cyber Daily.

 

Author Comment

by:mphillip85
ID: 40377739
in the first example i get this.


Error      1      Type expected            7      32      WindowsApplication2
Error      2      Identifier expected, 'string' is a keyword            7      55      WindowsApplication2
Error      3      Identifier expected, 'object' is a keyword            7      75      WindowsApplication2
Error      4      Identifier expected, 'string' is a keyword            7      94      WindowsApplication2
Error      5      Identifier expected, 'string' is a keyword            7      118      WindowsApplication2
Error      6      ; expected            7      141      WindowsApplication2
Error      7      Invalid token '=' in class, struct, or interface member declaration      9      17      WindowsApplication2
Error      8      Invalid token ';' in class, struct, or interface member declaration      9      30      WindowsApplication2
Error      9      Invalid token '=' in class, struct, or interface member declaration      10      23      WindowsApplication2
Error      10      Invalid token ';' in class, struct, or interface member declaration      35      WindowsApplication2
Error      11      Class, struct, or interface method must have a return type            11      9      WindowsApplication2
Error      12      Identifier expected            11      33      WindowsApplication2
Error      13      ; expected            11      34      WindowsApplication2
Error      14      Invalid token '=' in class, struct, or interface member declaration      27      WindowsApplication2
Error      15      Invalid token ';' in class, struct, or interface member declaration      12      39      WindowsApplication2
Error      16      Invalid token '.' in class, struct, or interface member declaration      13      15      WindowsApplication2
Error      17      Class, struct, or interface method must have a return type            13      16      WindowsApplication2
Error      18      Identifier expected            13      41      WindowsApplication2
Error      19      ; expected            13      42      WindowsApplication2
Error      20      Invalid token '=' in class, struct, or interface member declaration      14      25      WindowsApplication2
Error      21      Invalid token ';' in class, struct, or interface member declaration      14      38      WindowsApplication2
Error      22      Expected class, delegate, enum, interface, or struct            17      17      WindowsApplication2
Error      23      Type or namespace definition, or end-of-file expected            25      1      WindowsApplication2
0
 
LVL 32

Expert Comment

by:it_saige
ID: 40377752
Please provide the code that you are using.  Please be sure to include the desinger file code as well.

-saige-
0
 

Author Comment

by:mphillip85
ID: 40377914
CSharpExample.Extensions.Configure(comboBox1, "comboBox1"  , dataSet1, "dbobject.dbtable", "dbobject.dbtable");  
           
 dbobjectTableAdapter.Fill(this.dataSet1.dbobject);


I have it working now.  

going to try the datagrid now

thank you
0
 

Author Closing Comment

by:mphillip85
ID: 40377936
I felt  good about the code that was shown, which i just needed to adjust to my environment and it worked fine.  I am thankful for having to have it work 90% so i could learn the 10% that was needed to make it work in my solution.  

Great!
0

Featured Post

Enabling OSINT in Activity Based Intelligence

Activity based intelligence (ABI) requires access to all available sources of data. Recorded Future allows analysts to observe structured data on the open, deep, and dark web.

Join & Write a Comment

Suggested Solutions

Title # Comments Views Activity
What is MicroStrategy.NET? 2 45
Mutually exclusive checkbox in a gridview 18 41
LINQ question 7 22
fomat Json objects 6 17
Introduction Hi all and welcome to my first article on Experts Exchange. A while ago, someone asked me if i could do some tutorials on object oriented programming. I decided to do them on C#. Now you may ask me, why's that? Well, one of the re…
Exception Handling is in the core of any application that is able to dignify its name. In this article, I'll guide you through the process of writing a DRY (Don't Repeat Yourself) Exception Handling mechanism, using Aspect Oriented Programming.
Excel styles will make formatting consistent and let you apply and change formatting faster. In this tutorial, you'll learn how to use Excel's built-in styles, how to modify styles, and how to create your own. You'll also learn how to use your custo…
This video demonstrates how to create an example email signature rule for a department in a company using CodeTwo Exchange Rules. The signature will be inserted beneath users' latest emails in conversations and will be displayed in users' Sent Items…

705 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

Need Help in Real-Time?

Connect with top rated Experts

18 Experts available now in Live!

Get 1:1 Help Now