Creating Controls in a Class File
I selected Class Library option in C# Vis Studio Express to create a DLL which holds heaps of my commonl开发者_StackOverflow中文版y-used methods etc...
I'm trying to create a textbox in the class file, so that when I add the dll to another project all i have to type is:
MyControls.Create(TextBox);
...And it will create a text box and return it to me and then i can add it to the form.
I know how to create classes etc, so , my quesiton is... Why can't I use System.Windows.Forms is a class file? I have the following in my Class1.cs file:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace MyControls
{
public class class1
{
public object Create(object control)
{
System.Windows.Forms.TextBox t = new System.Windows.Forms.TextBox();
// textbox properties go here etc...
return control;
}
}
}
BUT the red squigly lines keep telling me that "The type of namespace 'Windows' does not exist in the namespace 'System' (Are you missing an assembly reference)?"
Have I forgotten to add something here...??
Thank you :)
It sounds as if you are missing a reference to System.Windows.Forms
; add that reference and your code should compile fine.
Side Note
I do get a bit curious about your method:
public object Create(object control)
{
System.Windows.Forms.TextBox t = new System.Windows.Forms.TextBox();
// textbox properties go here etc...
return control;
}
What is the input parameter used for? If you don't use it there is no need to pass it. Also, since the method is supposed to create controls for you, you could change the return type to Control
. That will remove the need to cast it in order to add it to the form. I would suggest design the method like this instead (making use of generics):
public T Create<T>() where T : Control
{
T control = Activator.CreateInstance<T>();
// textbox properties go here etc...
return control;
}
Yes you have to add a reference to the winforms dll (System.Windows.Forms) in the references of the project. This happens automagically when you make a win forms application but since you made just a dll it is not there.
Add the reference. Because you created a class library instead of a forms project, you don't have the necessary libraries reference.Go to Project menu>Add Reference... and select System.Windows.Forms from the .NET tab.
As said above, adding a reference to System.Windows.Forms
is enough.
Though I'm personnaly not fond of having common classes and controls all mixed up in the same assembly, but rather having one or more projects for the non-GUI code plus another project for the pure GUI code.
精彩评论