User Controls question

  • (2 Pages)
  • +
  • 1
  • 2

23 Replies - 2043 Views - Last Post: 10 May 2011 - 05:19 PM Rate Topic: -----

#1 kqmoney31  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 36
  • Joined: 08-May 11

User Controls question

Posted 08 May 2011 - 08:36 PM

Hi guys, Im trying to create user control for Visual C#. This is what I've accomplished already:
1. I created a windows form control library.
2. I created a combobox that displays the 12 months of the year (january,Feb,etc.) when it drops down.

What im trying to do is, I want this control to have string field monthName and a corresponding read-only property MonthName that returns the selected "month name" from the combobox. I also want to write an event handler for the combobox that updates the value of month name field whenever a new "month name" is selected from the combobox list. I've tried just about everything. How do i go about doing all this?

Is This A Good Question/Topic? 0
  • +

Replies To: User Controls question

#2 modi123_1  Icon User is online

  • Suitor #2
  • member icon



Reputation: 9201
  • View blog
  • Posts: 34,575
  • Joined: 12-June 08

Re: User Controls question

Posted 08 May 2011 - 08:53 PM

Quote

. I also want to write an event handler for the combobox that updates the value of month name field whenever a new "month name" is selected from the combobox list. I've tried just about everything. How do i go about doing all this?


What's wrong with using a 'selected index changed' or 'selected value changed' event from the combobox's list of events?

http://msdn.microsof...s.combobox.aspx

Then again if your combobox shows the text names already, why not have your read only control just hit that (the selected text or value depending on how you do it)?
Was This Post Helpful? 0
  • +
  • -

#3 kqmoney31  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 36
  • Joined: 08-May 11

Re: User Controls question

Posted 08 May 2011 - 09:13 PM

I also forgot to mention that this all has to be done by code. Can you go a lil bit more detail to help me solve all my problems?

View Postkqmoney31, on 08 May 2011 - 08:36 PM, said:

Hi guys, Im trying to create user control for Visual C#. This is what I've accomplished already:
1. I created a windows form control library.
2. I created a combobox that displays the 12 months of the year (january,Feb,etc.) when it drops down.

What im trying to do is, I want this control to have string field monthName and a corresponding read-only property MonthName that returns the selected "month name" from the combobox. I also want to write an event handler for the combobox that updates the value of monthName field whenever a new "month name" is selected from the combobox list. I've tried just about everything. How do i go about doing all this?


I made a mistake in this paragraph. I fixed it

This post has been edited by JackOfAllTrades: 09 May 2011 - 02:41 AM
Reason for edit:: Removed unnecessary quote

Was This Post Helpful? 0
  • +
  • -

#4 NotarySojac  Icon User is offline

  • D.I.C Regular
  • member icon

Reputation: 53
  • View blog
  • Posts: 428
  • Joined: 30-September 10

Re: User Controls question

Posted 08 May 2011 - 09:51 PM

1) Create a C# winforms project (or make a fancy user control if you think you will be reusing this control frequently in your upcoming project)

2) Drag and drop a combobox from the toolbox

3) Right click the combo box and select properties

4) For the property named "Items", Click the "..." button and add your months there
Note: These months are accessible as comboBox1.Items[0].Value (to get January if you made your dates right)
oops, see code below, winforms is different =0

5) Instead of viewing the properties, you now want to view the events, so click the Events tab.

6) Scroll down to the event "SelectedValueChanged" and double click the associated input box

You will now be brought into code. The function you're at will fire every time someone changes the item of the combo box. You could declare something like.

private string _monthName;

public string monthName
{
get
{
return _monthName;
}
}




and in your event function you can do


        private void Form1_Load(object sender, EventArgs e)
        {
            comboBox1.Items.Add("January");
            comboBox1.Items.Add("January2");
        }

        private void comboBox1_SelectedValueChanged(object sender, EventArgs e)
        {
            MessageBox.Show((string)comboBox1.SelectedItem);
            _monthName = (string)comboBox1.SelectedItem;
        }





That make sense?

This post has been edited by NotarySojac: 08 May 2011 - 10:01 PM

Was This Post Helpful? 0
  • +
  • -

#5 kqmoney31  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 36
  • Joined: 08-May 11

Re: User Controls question

Posted 08 May 2011 - 10:27 PM

Yea thanks a lot, that makes sense. Ill give this a try tomorrow. Thank you so much!

This post has been edited by JackOfAllTrades: 09 May 2011 - 02:40 AM
Reason for edit:: Removed unnecessary quote

Was This Post Helpful? 0
  • +
  • -

#6 tlhIn`toq  Icon User is offline

  • Please show what you have already tried when asking a question.
  • member icon

Reputation: 5520
  • View blog
  • Posts: 11,827
  • Joined: 02-June 10

Re: User Controls question

Posted 09 May 2011 - 08:27 AM

We have tutorials that go into deep detail on custom usercontrols.


The tutorials below walk through making an application including inheritance, custom events and custom controls.
Bulding an application - Part 1
Building an application - Part 2
Quick and easy custom events
Passing values between forms/classes
Was This Post Helpful? 0
  • +
  • -

#7 kqmoney31  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 36
  • Joined: 08-May 11

Re: User Controls question

Posted 09 May 2011 - 01:32 PM

View PostNotarySojac, on 08 May 2011 - 09:51 PM, said:

1) Create a C# winforms project (or make a fancy user control if you think you will be reusing this control frequently in your upcoming project)

2) Drag and drop a combobox from the toolbox

3) Right click the combo box and select properties

4) For the property named "Items", Click the "..." button and add your months there
Note: These months are accessible as comboBox1.Items[0].Value (to get January if you made your dates right)
oops, see code below, winforms is different =0

5) Instead of viewing the properties, you now want to view the events, so click the Events tab.

6) Scroll down to the event "SelectedValueChanged" and double click the associated input box

You will now be brought into code. The function you're at will fire every time someone changes the item of the combo box. You could declare something like.

private string _monthName;

public string monthName
{
get
{
return _monthName;
}
}




and in your event function you can do


        private void Form1_Load(object sender, EventArgs e)
        {
            comboBox1.Items.Add("January");
            comboBox1.Items.Add("January2");
        }

        private void comboBox1_SelectedValueChanged(object sender, EventArgs e)
        {
            MessageBox.Show((string)comboBox1.SelectedItem);
            _monthName = (string)comboBox1.SelectedItem;
        }





That make sense?


Hi thanks a lot it worked.....after i was done creating this i built it so that it could used in another project. If i wanted to create a Click event handler for a Button that retrieves the MonthName property from the user control and displays it in a MessageBox, how would i do that?
Was This Post Helpful? 0
  • +
  • -

#8 modi123_1  Icon User is online

  • Suitor #2
  • member icon



Reputation: 9201
  • View blog
  • Posts: 34,575
  • Joined: 12-June 08

Re: User Controls question

Posted 09 May 2011 - 01:35 PM

Double click on your button in the designer!
Was This Post Helpful? 0
  • +
  • -

#9 kqmoney31  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 36
  • Joined: 08-May 11

Re: User Controls question

Posted 09 May 2011 - 01:53 PM

View Postmodi123_1, on 09 May 2011 - 01:35 PM, said:

Double click on your button in the designer!


I know that but what exactly do I have to put in the button handler event?
Was This Post Helpful? 0
  • +
  • -

#10 modi123_1  Icon User is online

  • Suitor #2
  • member icon



Reputation: 9201
  • View blog
  • Posts: 34,575
  • Joined: 12-June 08

Re: User Controls question

Posted 09 May 2011 - 02:03 PM

What part of that is confusing? Accessing a property, or displaying a message box? I guess I am having issues reconciling what you are attempting to that level of a question. Oh well. I'll answer both parts.

Accessing a property

Console.WriteLine(<your user control>.MyProperty);



message boxes
     
System.Windows.Forms.MessageBox.Show("text goes here");



You should be able to combine everything nicely.
Was This Post Helpful? 0
  • +
  • -

#11 tlhIn`toq  Icon User is offline

  • Please show what you have already tried when asking a question.
  • member icon

Reputation: 5520
  • View blog
  • Posts: 11,827
  • Joined: 02-June 10

Re: User Controls question

Posted 09 May 2011 - 02:17 PM

View Postkqmoney31, on 09 May 2011 - 02:53 PM, said:

View Postmodi123_1, on 09 May 2011 - 01:35 PM, said:

Double click on your button in the designer!


I know that but what exactly do I have to put in the button handler event?


I would recommend you start with "Hello World" just like the other million+ coders out there. Then work your way up to the more advanced tasks like this.

The problem with taking on large, complex tasks like this when you are new to coding is that
  • it will frustrate you to the point of quitting,
  • you don't know enough about coding to know where to start or in what direction to design your program
  • You risk learning via the 'Swiss cheese' method where you only learn certain bits and pieces for the one project but have huge holes in your education.



Standard resources, references and suggestions for new programmers.

I am going to guess that you are trying to teach yourself C# without much guidance, a decent book or without knowing where to look. Sometimes just knowing where to look can make all the difference. Google is your friend.
Search with either "C#" or "MSDN" as the first word: "MSDN Picturebox", "C# Custom Events", "MSDN timer" etc.

But honestly, just typing away and seeing what pops up in Intellisense is going to make your self-education take 20 years. You can learn by trying to reverse engineer the language through banging on the keyboard experimentation - or you can learn by doing the tutorials and following a good "How to learn C#" book.

Free editions of Visual Studio 2010

May I suggest picking up a basic C# introductory book? There are so many great "How do I build my first application" tutorials on the web... There are dozens of "Learn C# in 21 days", "My first C# program" type books at your local book seller or even public library.

D.I.C. C# Resource page Start here
Intro to C# online tutorial then here...
C# control structures then here.
MSDN Beginner Developer video series
MSDN video on OOP principals, making classes, constructors, accessors and method overloading
MSDN Top guideline violations, know what to avoid before you do it.

The tutorials below walk through making an application including inheritance, custom events and custom controls.
Bulding an application - Part 1
Building an application - Part 2
Quick and easy custom events
Passing values between forms/classes

Working with environmental variables

Debugging tutorial
Debugging tips
Great debugging tips
It still doesn't work, article

Build a Program Now! in Visual C# by Microsoft Press, ISBN 0-7356-2542-5
is a terrific book that has you build a Windows Forms application, a WPF app, a database application, your own web browser.

C# Cookbooks
Are a great place to get good code, broken down by need, written by coding professionals. You can use the code as-is, but take the time to actually study it. These professionals write in a certain style for a reason developed by years of experience and heartache.

Microsoft Visual Studio Tips, 251 ways to improve your productivity, Microsoft press, ISBN 0-7356-2640-5
Has many, many great, real-world tips that I use all the time.

Writing a text file is always one of the first things people want to do, in order to store data like high-scores, preferences and so on
Writing a text file tutorial.
Reading a text file tutorial.


These are just good every-day references to put in your bookmarks.
MSDN C# Developers Center with tutorials
Welcome to Visual Studio

Have you seen the 500+ MSDN Code Samples? They spent a lot of time creating samples and demos. It seems a shame to not use them.

Let me also throw in a couple tips:
  • You have to program as if everything breaks, nothing works, the cyberworld is not perfect, the attached hardware is flakey, the network is slow and unreliable, the harddrive is about to fail, every method will return an error and every user will do their best to break your software. Confirm everything. Range check every value. Make no assumptions or presumptions.
  • Take the extra 3 seconds to rename your controls each time you drag them onto a form. The default names of button1, button2... button54 aren't very helpful. If you rename them right away to something like btnOk, btnCancel, btnSend etc. it helps tremendously when you make the methods for them because they are named after the button by the designer.
    btnSend_Click(object sender, eventargs e) is a lot easier to maintain than button1_click(object sender, eventargs e)
  • You aren't paying for variable names by the byte. So instead of variables names of a, b, c go ahead and use meaningful names like Index, TimeOut, Row, Column and so on

Was This Post Helpful? 0
  • +
  • -

#12 Nakor  Icon User is offline

  • Professional Lurker
  • member icon

Reputation: 444
  • View blog
  • Posts: 1,492
  • Joined: 28-April 09

Re: User Controls question

Posted 09 May 2011 - 02:20 PM

You need to create a public property in your user control that will allow you to access the value from the drop down control

Public string SelectedValue
{
    get { return dropdown.SelectedValue; }
}


This post has been edited by Nakor: 09 May 2011 - 02:26 PM

Was This Post Helpful? 0
  • +
  • -

#13 kqmoney31  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 36
  • Joined: 08-May 11

Re: User Controls question

Posted 09 May 2011 - 08:41 PM

View PostNakor, on 09 May 2011 - 02:20 PM, said:

You need to create a public property in your user control that will allow you to access the value from the drop down control

Public string SelectedValue
{
    get { return dropdown.SelectedValue; }
}



hi, thanks for your help, but when i run my program and click the button to show the messagebox, it says nullreferenceException was unhandled. What do i do?

If you need more info on what i'm trying to accomplish, heres the instructions on the program i have to make


Design a Windows MDI application with a container (parent) and a child form; in the MDI child form is a user control that contains a ComboBox

Form specifications:

1) For the MDI container: set the Form properties as follows: (1) set the StartPosition property so that the Form displays initially in the center of the screen (monitor); and (2) set the Text property to read "Container Form"; and include a File menu with commands New, a separater, and Exit
2) For the MDI child: set the Form properties as follows: set the Text property to read "Container Form"; and include a File menu with a single command Close
3) Merge the two menus so that the combined File menu displays in sequence: New, Close, a separater, and Exit

Specifications for a User Control:

1) Insert into the solution a new Windows Forms Control Library project to create a user control named "MonthList.cs"
2) In this project create a UserControl which contains a ComboBox that automatically displays the twelve months of the year (January, February, ... December) when it drops down
3) This control should have a string field monthName and a corresponding read-only property MonthName that returns the currently selected "month name" from the ComboBox; because it is read-only it will not be available in the "Properties" window, but only can be retrievedby a code statement
4) Write an event handler for the ComboBox that updates the value of the monthName field whenever a new "month name" is selected from the ComboBox list
5) Compile (Build) the composite library that contains the user control

Specifications for the MDI child form(s):

1) Place a copy of the MonthList user control into the MDI child form along with a Button
2) Create a Click event handler for the Button that retrieves the MonthName property from the user control and displays it in a MessageBox
Was This Post Helpful? 0
  • +
  • -

#14 Nakor  Icon User is offline

  • Professional Lurker
  • member icon

Reputation: 444
  • View blog
  • Posts: 1,492
  • Joined: 28-April 09

Re: User Controls question

Posted 09 May 2011 - 08:51 PM

Quote

3) This control should have a string field monthName and a corresponding read-only property MonthName that returns the currently selected "month name" from the ComboBox; because it is read-only it will not be available in the "Properties" window, but only can be retrievedby a code statement


Basically what I told you to do is what this step here is saying to do. Hopefully you didn't just copy and paste my code as it was meant as only an example and was not intended any other way. Have you completed all of the steps that you listed above? If not which steps are you specifically having a problem with? It would probably be easier for everyone involved if you would post what code you have so far and maybe we can give you a few pointers on where you're going off track.

This post has been edited by Nakor: 09 May 2011 - 08:51 PM

Was This Post Helpful? 0
  • +
  • -

#15 kqmoney31  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 36
  • Joined: 08-May 11

Re: User Controls question

Posted 09 May 2011 - 09:19 PM

Here's my code for my user control:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace Monthlist.cs
{
    public partial class UserControl1 : UserControl
    {
        public UserControl1()
        {
            InitializeComponent();
        }

        public string monthName;

        public string MonthName
        {
            get
            {
                return monthName;
            }
        }

        public void UserControl1_Load(object sender, EventArgs e)
        {
            comboBox1.Items.Add("January");
            comboBox1.Items.Add("January2");
        }
        public void comboBox1_SelectedValueChanged(object sender, EventArgs e)
        {
            
            monthName = (string)comboBox1.SelectedValue;
            
        }
    }
}



Heres the code for my child form:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace Project_10
{
    public partial class Child : Form
    {
        public Child()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            Console.WriteLine(userControl1.monthName);
            
        }

    }
}



using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace Project_10
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void newToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (this.IsMdiContainer)
            {
                Child child = new Child();
                child.IsMdiContainer = false;
                child.MdiParent = this;
                child.Show();
            }
            else
            {
                ((Form1)this.ParentForm).newToolStripMenuItem_Click(sender, e);
            }
        }
    }
}


Was This Post Helpful? 0
  • +
  • -

  • (2 Pages)
  • +
  • 1
  • 2