473,725 Members | 2,248 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Exposing form controls to other classes

Hi,

I'm trying to append text from another class to a generic richTextBox that
I've added to a Windows form. I can't seem to figure out how to expose the
richTextBox to append text to it.

Thanks in advance,

Chris
Nov 13 '05 #1
3 14160
Hi Nicholas,

Thanks for your reply. I had realized this early and actually tried writing
a public function to perform the actions as you had mentioned.
public void PostToBox(strin g msg)

{

richTextBox1.Ap pendText(msg);

}

However, being new to C#, I'm not sure how to call this function from my
other class (in the same namespace). Am I missing a uses statement or
something like that? It seems that I don't have access to the PostToBox
function when I attempted to call it: Form1.PostToBox ("hello");

Thanks for your time and patience,

Chris

"Nicholas Paldino [.NET/C# MVP]" <ni************ **@exisconsulti ng.com> wrote
in message news:ek******** ******@tk2msftn gp13.phx.gbl...
Chris,

You can set the access modifier of the rich text box to public, and then it will expose that member to anything that is holding a reference to your
form. However, I generally think that this is bad practice, and you should expose methods on your form that will perform the actions for you.
Something like a SetText method, or something of that nature.

Hope this helps.
--
- Nicholas Paldino [.NET/C# MVP]
- ni************* *@exisconsultin g.com

"Chris" <c w a n @ n o s p a m - v i g i l . c o m> wrote in message
news:%2******** ********@TK2MSF TNGP11.phx.gbl. ..
Hi,

I'm trying to append text from another class to a generic richTextBox that I've added to a Windows form. I can't seem to figure out how to expose

the
richTextBox to append text to it.

Thanks in advance,

Chris


Nov 13 '05 #2
Would you happen to have an example of how to make the object available
through a static property on a type?
"Nicholas Paldino [.NET/C# MVP]" <ni************ **@exisconsulti ng.com> wrote
in message news:uJ******** ******@TK2MSFTN GP10.phx.gbl...
Chris,

In VB6, an instance of the form with the same name as the type of the
form was always available. This is not the case in .NET. In .NET, a form
is just like any other object. If you want your objects to have access to
your form, then you have to pass it to them, or make it available through
something like a static property on a type.
"Chris" <c w a n @ n o s p a m - v i g i l . c o m> wrote in message
news:%2******** ********@tk2msf tngp13.phx.gbl. ..
Hi Nicholas,

Thanks for your reply. I had realized this early and actually tried

writing
a public function to perform the actions as you had mentioned.
public void PostToBox(strin g msg)

{

richTextBox1.Ap pendText(msg);

}

However, being new to C#, I'm not sure how to call this function from my
other class (in the same namespace). Am I missing a uses statement or
something like that? It seems that I don't have access to the PostToBox
function when I attempted to call it: Form1.PostToBox ("hello");

Thanks for your time and patience,

Chris

"Nicholas Paldino [.NET/C# MVP]" <ni************ **@exisconsulti ng.com>

wrote
in message news:ek******** ******@tk2msftn gp13.phx.gbl...
Chris,

You can set the access modifier of the rich text box to public,
and
then
it will expose that member to anything that is holding a reference to your form. However, I generally think that this is bad practice, and you

should
expose methods on your form that will perform the actions for you.
Something like a SetText method, or something of that nature.

Hope this helps.
--
- Nicholas Paldino [.NET/C# MVP]
- ni************* *@exisconsultin g.com

"Chris" <c w a n @ n o s p a m - v i g i l . c o m> wrote in message
news:%2******** ********@TK2MSF TNGP11.phx.gbl. ..
> Hi,
>
> I'm trying to append text from another class to a generic
richTextBox that
> I've added to a Windows form. I can't seem to figure out how to

expose the
> richTextBox to append text to it.
>
> Thanks in advance,
>
> Chris
>
>



Nov 13 '05 #3
As others have said, once you see that a form is just a class, then anything
is possible and you will see many ways to do these kind of things. For
example, to have bidirectional links between two forms (say the MainForm and
a LogForm) can be done a couple ways.
1) MainForm - As you probably want to keep the log form open but hidden all
the time, you can add a private var to your declaration section in MainForm.
Then in the load method, create an instance of the LogForm for the rest of
MainForm (or others) to use. Now add a Public property (or public method)
to LogForm that returns a ref (i.e. getter) to the richtextbox on the
LogForm. Now MainForm has everything it needs. It has a ref to LogForm and
can "see" the richtextbox to append some text. It is probably better to use
a Public method in LogForm to do this as you "contain" more logic in LogForm
that way and handle errors, returns and don't expose your raw control to
MainForm which could help reduce problems along the way.
2) So now you can start LogForm from MainFrom and append text as you need.
But what if LogForm needs to check a public field or public property in
MainForm to see if something is set or not (i.e. an AllowClearLog flag or
something else set in an options dialog.) Or maybe it too needs to append
some text to a richtextbox in main after it does something usefull. LogForm
is constructed and running, but it does not now anything about MainForm and
has no reference to it. For this, standard class constructors can help. As
a Form is first a class like any other, you can instantiate a form using a
constructor and passing in values or ref types. This is what we need and
how LogForm will know how to ref back to MainForm to see Public Properties
or public fields or public methods. So in MainForm, when you load the
instance of the LogForm, do it this way "logForm = new LogForm(this);" .
This passes the ref to MainForm to the LogForm(MainFor m mainForm)
constructor. You need to add/change the LogForm(MainFor m mainForm)
constructor in LogForm. Remember to use "MainForm" type and not "Form" or
"Object" as you will have to down-cast Form to MainForm anyway in your code
to "see" MainForm's public properties.

Now MainForm can see LogForm and visa-versa. When you see the linkages, you
can use this for many kinds of inter-form/class communications. Here is an
example:

MainForm
======
using System;
using System.Drawing;
using System.Collecti ons;
using System.Componen tModel;
using System.Windows. Forms;
using System.Data;

namespace ReferenceBetwee nForms
{
/// <summary>
/// Summary description for Form1.
/// </summary>
public class MainForm : System.Windows. Forms.Form
{
private System.Windows. Forms.Button btnShowLog;
private System.Windows. Forms.RichTextB ox richTextBox1;
/// <summary>
/// Required designer variable.
/// </summary>
private System.Componen tModel.Containe r components = null;
private LogForm logForm; //private var to hold common reference to
LogForm.

public MainForm()
{
//
// Required for Windows Form Designer support
//
InitializeCompo nent();

//
// TODO: Add any constructor code after InitializeCompo nent call
//
}

/// <summary>
/// Clean up any resources being used.
/// </summary>
protected override void Dispose( bool disposing )
{
if( disposing )
{
if (components != null)
{
components.Disp ose();
}
}
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 InitializeCompo nent()
{
this.btnShowLog = new System.Windows. Forms.Button();
this.richTextBo x1 = new System.Windows. Forms.RichTextB ox();
this.SuspendLay out();
//
// btnShowLog
//
this.btnShowLog .Location = new System.Drawing. Point(224, 232);
this.btnShowLog .Name = "btnShowLog ";
this.btnShowLog .TabIndex = 0;
this.btnShowLog .Text = "Show Log";
this.btnShowLog .Click += new System.EventHan dler(this.btnSh owLog_Click);
//
// richTextBox1
//
this.richTextBo x1.Location = new System.Drawing. Point(24, 32);
this.richTextBo x1.Name = "richTextBo x1";
this.richTextBo x1.Size = new System.Drawing. Size(240, 152);
this.richTextBo x1.TabIndex = 1;
this.richTextBo x1.Text = "";
//
// MainForm
//
this.AutoScaleB aseSize = new System.Drawing. Size(5, 13);
this.ClientSize = new System.Drawing. Size(320, 273);
this.Controls.A dd(this.richTex tBox1);
this.Controls.A dd(this.btnShow Log);
this.Name = "MainForm";
this.Text = "Main";
this.Load += new System.EventHan dler(this.MainF orm_Load);
this.ResumeLayo ut(false);

}
#endregion

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

private void MainForm_Load(o bject sender, System.EventArg s e)
{
logForm = new LogForm(this);
}

private void btnShowLog_Clic k(object sender, System.EventArg s e)
{
logForm.LogForm RichText.Append Text("Main Form Showed LogForm and appended
this text.\n");
logForm.LogThis ("Main Form appended this text using Public Method.\n");
logForm.Show();
}

public RichTextBox MainFormRichTex t
{
get { return this.richTextBo x1; }
}
} //End MainForm Class
}

LogForm
===========
using System;
using System.Drawing;
using System.Collecti ons;
using System.Componen tModel;
using System.Windows. Forms;

namespace ReferenceBetwee nForms
{
/// <summary>
/// Summary description for Form2.
/// </summary>
public class LogForm : System.Windows. Forms.Form
{
private System.Windows. Forms.RichTextB ox richTextBox1;
private System.Windows. Forms.TextBox tbParent;
private System.Windows. Forms.Label label1;
private System.Windows. Forms.Button btnOK;
/// <summary>
/// Required designer variable.
/// </summary>
private System.Componen tModel.Containe r components = null;
private System.Windows. Forms.Button btnClearLog;
private MainForm mainForm;

public LogForm(MainFor m parentForm)
{
//
// Required for Windows Form Designer support
//
InitializeCompo nent();

//
// TODO: Add any constructor code after InitializeCompo nent call
//
mainForm = parentForm; //Set private var "mainForm" so logger always has
reference to mainform.
}

/// <summary>
/// Clean up any resources being used.
/// </summary>
protected override void Dispose( bool disposing )
{
if( disposing )
{
if(components != null)
{
components.Disp ose();
}
}
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 InitializeCompo nent()
{
this.richTextBo x1 = new System.Windows. Forms.RichTextB ox();
this.tbParent = new System.Windows. Forms.TextBox() ;
this.label1 = new System.Windows. Forms.Label();
this.btnOK = new System.Windows. Forms.Button();
this.btnClearLo g = new System.Windows. Forms.Button();
this.SuspendLay out();
//
// richTextBox1
//
this.richTextBo x1.Location = new System.Drawing. Point(8, 40);
this.richTextBo x1.Name = "richTextBo x1";
this.richTextBo x1.Size = new System.Drawing. Size(272, 168);
this.richTextBo x1.TabIndex = 0;
this.richTextBo x1.Text = "";
//
// tbParent
//
this.tbParent.L ocation = new System.Drawing. Point(64, 8);
this.tbParent.N ame = "tbParent";
this.tbParent.T abIndex = 1;
this.tbParent.T ext = "";
//
// label1
//
this.label1.Loc ation = new System.Drawing. Point(16, 8);
this.label1.Nam e = "label1";
this.label1.Siz e = new System.Drawing. Size(48, 23);
this.label1.Tab Index = 2;
this.label1.Tex t = "Parent:";
//
// btnOK
//
this.btnOK.Loca tion = new System.Drawing. Point(200, 248);
this.btnOK.Name = "btnOK";
this.btnOK.TabI ndex = 3;
this.btnOK.Text = "OK";
this.btnOK.Clic k += new System.EventHan dler(this.btnOK _Click);
//
// btnClearLog
//
this.btnClearLo g.Location = new System.Drawing. Point(200, 216);
this.btnClearLo g.Name = "btnClearLo g";
this.btnClearLo g.TabIndex = 4;
this.btnClearLo g.Text = "Clear";
this.btnClearLo g.Click += new
System.EventHan dler(this.btnCl earLog_Click);
//
// LogForm
//
this.AutoScaleB aseSize = new System.Drawing. Size(5, 13);
this.ClientSize = new System.Drawing. Size(292, 277);
this.Controls.A dd(this.btnClea rLog);
this.Controls.A dd(this.btnOK);
this.Controls.A dd(this.label1) ;
this.Controls.A dd(this.tbParen t);
this.Controls.A dd(this.richTex tBox1);
this.FormBorder Style = System.Windows. Forms.FormBorde rStyle.FixedDia log;
this.Name = "LogForm";
this.StartPosit ion = System.Windows. Forms.FormStart Position.Center Parent;
this.Text = "Log";
this.Closing += new
System.Componen tModel.CancelEv entHandler(this .LogForm_Closin g);
this.Load += new System.EventHan dler(this.LogFo rm_Load);
this.ResumeLayo ut(false);

}
#endregion

private void btnOK_Click(obj ect sender, System.EventArg s e)
{
this.Hide();
}

private void LogForm_Load(ob ject sender, System.EventArg s e)
{
mainForm.MainFo rmRichText.Appe ndText("LogForm was loaded and appended
this text to MainForm using reference passed to LogForm() constructor.");
this.tbParent.T ext = mainForm.Name;
}

public void LogThis(string logText)
{
//One option is to use a public method to log text.
//This is probably preferred as you "contain" all append and error
//logic in the class where it belongs (i.e. the LogForm.)
this.richTextBo x1.AppendText(l ogText);
}

private void btnClearLog_Cli ck(object sender, System.EventArg s e)
{
this.richTextBo x1.Clear();
}

private void LogForm_Closing (object sender,
System.Componen tModel.CancelEv entArgs e)
{
e.Cancel = true;
this.Hide();
}

public RichTextBox LogFormRichText
{
//Another option is to use a public Property to return a ref. to
//the RichTextBox and let MainForm logic append.
get { return this.richTextBo x1; }
}
}
}

HTH
--
William Stacey, DNS MVP
Nov 13 '05 #4

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

4
2446
by: Tony W | last post by:
Hi, I am trying to write a simple application to retrieve data from the Windows registry and insert it into textboxs on a windows form. So far I have one namespace containing two classess. The first class handles the form generation - (this was done using GUI form designer).
4
1992
by: Adam Clauss | last post by:
This may be more of a Visual Studio question than a C# question, but it came up within the context of a C# app, so here it is. In a Windows Form or a Web Form application, you can drag various DataAdapters and create DataSets bound to them so everything is strongly typed - a very nice feature. Why in the world can this not be done the same way for ANY type of application (say, Console, or Class Library). What do these features have...
8
2324
by: Tim Geiges | last post by:
Since I am being challenged with learning c# I figured I could pass some of the pain on to you guys :-) I have another question(this one is important for me to fix before I can get my app to Beta) My app (an image viewer) opens with a Main form with a file explorer if you open the program with the exe, but opens with the ImageView form if you double click an image file, if you want to see the Main form once the ImageView is open the...
3
2980
by: Dave | last post by:
Please - anyone that can help. I am getting confusing results while trying to expose a collection from a web service. I have a webservice in which a web method accepts a collection as a parameter and returns an array of datasets. The collection consists of database connection objects. Based on the simple hierarchy below, you can see that starting with the
2
1575
by: Yuk Tang | last post by:
I've satisfactorily got an axwebbrowser control on a form within a panel, suitably positioned and sized, and now I want to display a webpage on it. This is not normally a problem when I have the control as a uniquely named object, since I would just use the axweb.Navigate or Navigate2 method to send it to the right page. However, it's part of a controls collection, accessible only via its place in the collection.
9
1657
by: Dimsion | last post by:
Hi, How do i expose all my forms and it controls to other form in the project? I want to be able to add a form and some control on it, this then be available to all other forms. form1 click event: 'this allow me to change the textbox on form2 from form1 Form2.text="" 'this allow me to add item to form2 from form1
2
1844
by: Rich | last post by:
Greetings, I observed that in VB2005 the designer generated code is hidden. The initialize code appears to be stored in a different module than the Form's class module. But the form's class module constructor is in the same module as the Form class (obviously). Well, I exposed the constructor, which was originally unexposed. Is there a way to hide it again after exposing it? I don't mean collapse, I mean hide it the way it was...
4
13357
by: Toze | last post by:
I'm using a assembly to load my apllication (ex: Mobi.exe), and now I need to list all forms in my apllication and list all controls (ex: txtname;btnname) inside of each form.
3
4691
by: bsturg21 | last post by:
Hello, I have a windows form that has a series of linklabels on it, and I need to have each linklabel, when clicked, open a separate windows form that has a single paramter passed into it. The form that has the System.Windows.Forms.LinkLabel controls on it is in a different project and under a different namespace from the file where the LinkLabel_LinkClicked events are, so I can't just do frm.ShowDialog under the LinkClicked method. ...
0
8889
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
8752
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
1
9179
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
9116
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
8099
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
0
6011
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
4784
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
2
2637
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2157
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.