newbie question: read form properties from another class


Hi,

I am sorry for this n00b question, but I'm stumped.

I created a form application (using C#.NET Express). For now, it is a 
simple, singe form, that contains 1 button and 1 textbox.

The button calls a method in another class. My question: how do I read 
the forms' textbox text from that class?

My problem seems to be getting a proper reference to the form in my 
class. My background is VB6, where this was straightforward.

I tried the following:
-make the textbox public,
-create a public property in the form, that returns the textbox text,
-passing the form object ('this') to a method in the called (static) 
class
-passing the form object ('this') to the class' constructor (non-static 
class)

But I can't seem to get to the form's textbox text, as Intellisense and 
the debugger keep telling me.

I feel like I am going about this the wrong way, and that I am 
misunderstanding some key language concept.

Would really appreciate any pointers to get me going.

tia
arno
0
rno
2/5/2010 12:22:30 AM
dotnet.languages.csharp 1931 articles. 0 followers. Follow

5 Replies
1026 Views

Similar Articles

[PageSpeed] 54

rno wrote:
> 
> Hi,
> 
> I am sorry for this n00b question, but I'm stumped.
> 
> I created a form application (using C#.NET Express). For now, it is a 
> simple, singe form, that contains 1 button and 1 textbox.
> 
> The button calls a method in another class. My question: how do I read 
> the forms' textbox text from that class?

You need to do two things:

   � Ensure that the other class has a reference to the form class instance

   � Ensure that the form class itself has a property that encapsulates 
the text property you want access to

> My problem seems to be getting a proper reference to the form in my 
> class. My background is VB6, where this was straightforward.

To some extent, it was straightforward only because in VB6, the language 
provided default instances and unrestricted access to types.  .NET is a 
lot strictly, and C# more strict than VB.NET even.

> I tried the following:
> -make the textbox public,

That could work, if everything else is correct, but it's a REALLY BAD 
IDEA.  Expose "interface", not implementation.

> -create a public property in the form, that returns the textbox text,

This is part of a complete solution.

> -passing the form object ('this') to a method in the called (static) 
> class

This could be part of a complete solution.

> -passing the form object ('this') to the class' constructor (non-static 
> class)

This also could be part of a complete solution.

> But I can't seem to get to the form's textbox text, as Intellisense and 
> the debugger keep telling me.

Well, you seem to be on the right track.  So obviously, you just haven't 
gotten quite the right combination of elements together.

But without a concise-but-complete code example to _show_ us what 
doesn't work, it's not possible to explain what's wrong.

What I _can_ do is offer a short, incomplete code example illustrating 
the basic technique you need:

   class Form1 : Form
   {
     public string TextBox1Text
     {
       get { return textBox1.Text; }
       set { textBox1.Text = value; }
     }

     private void SomeMethod()
     {
       OtherClass oc = new OtherClass(this);

       oc.SomeMethod();
     }

     // Normally in the Form1.Designer.cs file; here for
     // illustration purposes only:
     private TextBox textBox1;
   }

   class OtherClass
   {
     private Form1 _form1;

     public OtherClass(Form1 form1)
     {
       _form1 = form1;
     }

     public SomeMethod()
     {
       string str;

       // Retrieve the text:
       str = _form1.TextBox1Text;

       // Or set the text:
       _form1.TextBox1Text = "Set from OtherClass.SomeMethod()";
     }
   }

Hopefully, when you compare the above to whatever code you actually 
tried, you'll see one or more things that are different in a significant 
way, and you can see what the correct approach is.

Now, one thing to keep in mind is that there may be other reasons to 
approach this problem differently.  It should be unusual to have to some 
helper class that actually knows the type of the caller, as would be 
required in the above example.

But, without knowing more about the broader problem you're trying to 
solve, I can't really offer advice about how to avoid the above pattern 
completely.  So for now, it will have to do.  :)

Pete
0
Peter
2/5/2010 12:42:01 AM
On 2/5/2010 8:22 AM, rno wrote:
>
> I created a form application (using C#.NET Express). For now, it is a
> simple, singe form, that contains 1 button and 1 textbox.
>
> The button calls a method in another class. My question: how do I read
> the forms' textbox text from that class?
>

In addition to what Peter has wrote, if nothing in the AnotherClass that 
suggest the need of a reference to your Form1 object, you can just have 
that method to accept a string argument.

class AnotherClass
{
   ...

   void SomeMethod(string text)
   {
     // do something
   }
}

So, when you have the instance of AnotherClass (for example: 
anotherClassInstance), you can just pass the textBox1.Text to the 
SomeMethod() argument.

anotherClassInstance.SomeMethod(textBox1.Text);

Regards.
0
kndg
2/5/2010 12:56:10 AM
"rno" <none@empty.no> wrote in message 
news:MPG.25d5831f2e73d60c98968e@textnews.kpn.nl...
> Would really appreciate any pointers to get me going.

I strongly agree with kndg's response. It's about as simple as it gets and 
you don't need to refer to the textbox or form inside your class. You might 
find it a pita but C# is actually doing what it is designed to do here. VB6 
let you do it the wrong way where C# at least directs you towards to correct 
method. Think of your class as a block of code that could be used by any 
object, not just the one form. By placing references back to the textbox 
into that class you make the class restricted to that form only and stops it 
from being reused.

Michael 


0
Michael
2/5/2010 2:14:00 AM
Thank you all for your valuable input. I am sure I will get it working
now somehow!

arno
0
rno
2/5/2010 10:14:00 AM
Got it. I was so close :) I failed to properly get a reference to the 
form, because I did not realise that it had to be of type 'Form1', not 
Form. I suppose that's [bleep] obvious, just not to me :) I'm 
learning...

tx again
arno

In article <hnrnm5dutu7sgidlu8vgkjv0lnuj8mua6r@4ax.com>, nospam@fake.org 
says...> 
> Thank you all for your valuable input. I am sure I will get it working
> now somehow!
> 
> arno


0
rno
2/5/2010 11:31:42 AM
Reply:

Similar Artilces:

asap utilities question
I have Msft. Excel Vsn 2002 and latest vsn. of ASAP Utilities. I used ASAP Utilities to merge single rows of data together so that more than one row will fit on a single line of text. My question now, is, is it possible using ASAP Utilities to separate the data that has been merged back into single rows of data? All information welcomed! Aaron ...

Isinteg Warning Message Question
I ran isinteg -pri -test alltests. I came up with 506 warnings. There are basically 4 types of warnings. They are below. Are these something I need to worry about? What should I do? thanks stewart sschwartz@nal.usda.gov ================================== Warning: MsgFolder 165 (Fid=0001-0000000D1864, Mid=0001- 0000000D559D, Inid=0001-000000F33436): PR_READ_RECEIPT_REQUESTED(0029000B) prop in Messages table and MsgFolder table do not match. Warning: MsgFolder 4 (Fid=0001-0000086DC911, Mid=0001- 00000436F972, Inid=0001-000004A583F1): Error JET_errRecordNotFound seeking to INID for this ...

Word2007. Checkbox. No Form
Hello! We have a document (not a form) that we would like to use checkboxes in. This document has a couple of sections where it would be useful if the user could check if something is applicable. We can't protect the whole document. Thank you for your help! Stacey I actually used this feature in a form this morning. Although you don't say what version of Word you are using, you can access the Control Toolbox toolbar in Word 2003, or in Word 2007, it is on Developer tab. To show the developer tab, click the Microsoft Office Button and then click Word Options. S...

Outlook Hangs Reading Messages
I am running Windows XP Pro & Outlook 2003 via POP3 & Symantec AV I had to reinstall everything on my pc and now find when I double click an email outlook hangs for roughly a minute and then it finally opens, I have tried a data compact, reinstalling outlook and creating a new pst then importing but it still happens Does anyone have any ideas? It's driving me mad Thanks Daz Try deleting and recreating the profile as one of your steps in troubleshooting: http://www.howto-outlook.com/Faq/newprofile.htm -- K. Orland Thoughts lead on to purposes; purposes go forth in action; ...

Macro for Sharepoint List and another Table?? Same # records?
I am creating a database which we have a form made up of prepopulated data (from a sharepoint list) and also data input needed by a user (for example, comments, etc.). I have two tables: one sharepoint list that is linked to sharepoint website and another table that houses the additional user inputs [table 2]. I have linked the files based on the primary key. So, every record in my table 2 has a plus sign and it will expand and you will see the linked data from the sharepoint list. Is there a way that I can automatically create a record for every corresponding record ...

Outlook rule to move read message from Blackberry
I have Outlook configured with a Blackberry server and want to set up a rule to mange messages marked as read: For example. 1. I'm away from the office, Outlook is closed. 2. I read an email on my Blackberry, which marks the message "read" 3. When I return to the office and open Outlook I want to: a. Apply a rule to my inbox that states: If message is marked as read, move to folder "read messages" b. All unread messages will remain in the inbox. I'm a heavy user of rules but I can't find a way to identify "read" messages. Any thoughts? view360@gm...

changing values of one field based on another
How can I best change the values of one field in a table based on values of another field of the same table. We have an existing table of thousands of entries and I would like to use the following logic to populate a new boolean field. If field1 = "Done" Then BooleanFieldCompleted = True I have some Excel VBA experience but limited Access. I dont want to do this manually! Any assistance appreciated. In general, you'd use an Update query. However, in this case I don't see why you'd need such a field. Why not just create a query with a computed field that returns True...

Dotfuscator question
Hello Everybody !!! When i create programm using C# i must understand that my programm from exe - module can be converted to the source file by Reflector. In Order do not allow do this i must use dotfuscator, but i did not find any free normal dotfuscator. May be someone tell me what can i do cause now as think we have interesting paradox. We 've got free technology but if we want to protect our products we must buy expensive commercial dotfuscators. Alex Dmitriev You should post this message in a newsgroup which discusses managed code. This newsgroup does not have much managed traff...

I would like to know how to set up a 'fill in the blanks' form?
I would like to set up a templet of sorts to fill in the blanks for certificates. ...

question on the rules wizard
When clikcing on the Rules Wizard, Outlook locks up - consistently. Has anyone got a remedy for this? Thank you, rich rpage@concerto.com ...

Copying Data in a cell in one sheet to a cell in another sheet
I've run into a problem trying to copy data from a cell in one sheet to another. I have a spreadsheet called "rating" which contains a number of formula that calculates a final number. I also have a spreadsheet called "Final" that copies over the information from "Rating". In "Final", I'm trying to copy a number from "Rating" into a particular cell. I put in =Rating! G89, but it won't work. When I press enter, a window pops up "Update value:Rating". I press enter again and in the cell where I want the number ...

OE questions
Ok, I have two questions: 1. With Thunderbird I can use this with a hotkey manager to compose a new message with Tbird "D:\Program Files\Mozilla Thunderbird \thunderbird.exe -compose" -- how can I do the same for Outlook Express and Outlook 2003? 2. When I go to load Outlook Express I get this error message, followed by the error message below it: http://i180.photobucket.com/albums/x296/gwar_1/Untitled-3.png how can I fix this and use Outlook Express? Thanks! posted to the outlookexpress newsgroup via crosspost --=20 Peter Please Reply to Newsgroup for the benefit of others Re...

question about Time
How to make the time result for example if it�s ( 1:01 ) or higher shows only as ( 1:00 ) and if it�s Lower like ( 0:59 ) or less it will show the same result in this case ( 0:59 ) Any idea & suggestions. Thanks, almufadda@hotmail.com ------------------------------------------------ ~~ Message posted from http://www.ExcelTip.com/ ~~View and post usenet messages directly from http://www.ExcelForum.com/ Using Ron deBruin's google addin and asking for subject round time, I get http://tinyurl.com/wgua -- Don Guillett SalesAid Software donaldb@281.com "saud" <saud.xgc4...

MFC project with my classes
I have got a project that uses MFC. I want to expand the functionality of the project by adding a few of my own classes to it. But I don't know where should I create objects of my new classes so that I can access them, I know the WinMain function resides in CWinApp class and my project has a class inherited from the CWinApp class, but where should I define my own objects I can't figure it our. Can anybody help? Adrian wrote: > I have got a project that uses MFC. I want to expand the functionality > of the project by adding a few of my own classes to it. But I don't > kno...

Report to show Item Class Distribution Amounts
We would like to create a report, using Crystal Reports, that would show the following: dollar amount break down of the Sales Distribution accounts (COGS and Sales) per item class based on a date range. What is the most accurate way of going about this? We could only think of this method: (in short) sum the Ext Price based on SOP30300.CSLSINDX and SLSINDX and hope it matches the SOP10102 summed distribution amounts. Any advice would be appreciated. Thanks in advance. With the SLSINDX you would use the Extended Price and the CSLSINDX you would use Extended Cost. You would probably ...

HQ Licensing question V.2
I have a client running HQ client at 8 stores + HQ server at the warehouse. They would like to be able to use transfers from the warehouse to the stores, so I would have to setup a new PC running Store Ops and a new database, however, in order for the transfers to take place, I need a HQ Client License correct? Do I also need a POS key? I appreciate any insights you may have. Thanks in advance Hi Phil yes - you'll need an HQ Client license so it can exchange with your headquarters - "export" the wh database as you would any store from HQ no - you won't need a PO...

item class table
I am creating SOP IM import. I need to fill the distribution fields with a rev account that is part of the item class. I would like to find a table that would hold the item class accounts. I looked in IV40400 and did not see any distribution accounts. What is the best table to pull these accounts. If the accounts have been defined on the Item Class, they will appear on the records in the IV40400 table. They're in the fields IVIVINDX, IVIVOFIX, etc - and they're just the keys to the actual account definitions in the GL00100 table. If a particular account type isn't defined ...

Cant read one instance of recurring appointment
The problem we're having is a little different that what I've seen posted. A user randomly gets the message "Cant read one instance of recurring appointment. close any open appointments and try again, or recreate the appointment" several times a day. When you click OK the same message appears several times. Outlook doesn't indicate which recurring appointment is having the problem and the message just pops up at various times even if the user isn't in the calendar. We've deleted the Frmcache file and run the clean profile switch, but that hasn't worked. Has an...

Picture control on a form
What is the best way to fill a form with a picture control so that when the client window is resized the picture control will fill the form? -- Just Al Take a look at this and see if this is what you want: http://www.codeproject.com/dialog/bmpdlg01.asp Tom "Al" <Al@discussions.microsoft.com> wrote in message news:5BEA0FA2-3F95-4090-B908-A75DBF1D19DE@microsoft.com... > What is the best way to fill a form with a picture control so that when > the > client window is resized the picture control will fill the form? > -- > Just Al Thank You! -- Just Al &...

Null value in form not trapped by beforeupdate event
I have a form in Access 2003 linked to a SQL Server 2005 table. When I clear the value in a textbox (bound field is varchar and is required), I want the before update event to run to tell the user the value cannot be null. When I press the tab button to move to the next field after clearing the texbox, the before update event is not triggering and instead I'm getting the following error: You tried to assign the Null value to a variable that is not a Variant data type. (Error 3162) How can I prevent nulls before and this error from triggering? Thanks! ...

Accessing another user's calendar OL2000/OL2003/Ex2000
Here's the situation: Running Exchange2000, v 6.0, sp4. Users are on XP/OL2003 or NT/OL2000. (we're in the process of upgrading all of the workstations to XP.) VIP user is on XP/OL2003. He can access his calendar just fine on his workstation. His secretary and other office admin type people are still on NT/OL2000. They have reviewer or editor rights to his calendar. They try to access his calendar by chosing File/Open/Other User's Folder... and put in his name and calendar. When they do this, the process hangs. In Task Manager, Outlook is "Running." End the Outloo...

MS Project 2007 question
Hello, I am developing a simple schedule with no resources but 2 tasks out of 100 are hazardous and I would like to make the schedule so that when these tasks occur, no other tasks can occur. In other words, even though all tasks are moving around as the schedule is being developed, I would like to make sure no other tasks can be scheduled wherever these 2 hazardous tasks fall. These 2 tasks are serial to every other task in the schedule. Is there a way to do this? Thanks for your help. Mike Create two milestones. Use milestone 1 as the successor task to all tasks th...

WLM transfer to another computer
Hi, I finally moved from Windows 7 RTM to Win7 Pro 64. I did it by installing the new OS on a brand new hard drive, then installed my old hard drive in a 2.5" external enclosure. I've been successful in moving most of my files and settings over, but WLM is the exception. Can someone help answer these questions for me: 1. Where are the actual mail files stored? 2. Where is the account login info stored? 3. In Outlook and OE installing on a new computer, even after moving files, prompted for a full redownload off of the POP server. Anyway to avoid this? Is ther...

Disappearing data in sync'd forms
I have a small sized text box in a form called frmMain. This text box may or may not contain a large amount of text. If the text box does contain alot of text I want to open up a new form called frmLargeText that contains a larger text box to allow the user to easily see and edit the large amount of text. I also need the two forms to stay in sync. i.e. if the user moves to a new record then both forms move to the same record. I thought I could do this by setting the recordset of frmLargeText to equal the recordset of frmMain as follows: Dim frm as Form_frmLargeText Dim rst As DAO.Rec...

Perhaps another Money alternative?
After years of their saying "what's Windows?" I not that the following announcement: --- Announcement: GnuCash 2.1.1 Release - 2007-04-28 17:47 GnuCash 2.1.1 released The GnuCash development team proudly announces GnuCash 2.1.1 aka "Bug-begone", the second of several unstable 2.1.x releases of the GnuCash Open Source Accounting Software which will eventually lead to the stable version 2.2.0. With this new release series, GnuCash is available on Microsoft Windows for the first time... --- I haven't checked into this further just yet, but that will certainly be...