[C#] Global Variables.

Discussion in 'Programming General' started by mvrb, Feb 8, 2009.

Thread Status:
Not open for further replies.
[C#] Global Variables.
  1. Unread #1 - Feb 8, 2009 at 3:34 AM
  2. mvrb
    Joined:
    Feb 8, 2009
    Posts:
    1
    Referrals:
    0
    Sythe Gold:
    0

    mvrb Newcomer

    [C#] Global Variables.

    Hello, I have 2 windows forms in my C# application. I want a string to be able to communicate with Form2. Like if I click on button1 then it will be

    textBox1.Text = myString; // this is form 2's textBox.

    And I heard something about Global Variables, but I've been searching around, but I didn't find anything. So does anyone know how I can get myString from Form1 to Form2 ?
     
  3. Unread #2 - Feb 8, 2009 at 3:24 PM
  4. hampe-92
    Joined:
    Jul 10, 2008
    Posts:
    328
    Referrals:
    0
    Sythe Gold:
    0

    hampe-92 Forum Addict

    [C#] Global Variables.

    This is realy easy, you can create a new class, let's call it MyClass

    in MyClass, create a public string and name in something (e.g myString)
    Code:
    using System;
    using System.Collections.Generic;
    using blah blah blah...
    
    namespace FormsApp
    {
        class MyClass
        {
               public static string MyString;
        }
    }
    
    then in Form1

    Code:
    private void button1_click(object sender, EventArgs e)
    {
    MyClass.myString = textBox1.Text;
    }
    
    and from Form2 (let's say we want the text in textbox1 as a title on form2..
    Code:
    private void Form2_load(object sender, EventArgs e)
    {
       this.Title = MyClass.myString;
    }
    
    it's easy as that...
    don't just copy and past cause it probably wont work since i wrote it in the reply box so probably some wrong casing or misspelling, but I guess you can figure it out ;)
     
  5. Unread #3 - May 29, 2009 at 5:14 PM
  6. Pur3 Bull3t
    Joined:
    May 29, 2009
    Posts:
    46
    Referrals:
    0
    Sythe Gold:
    0

    Pur3 Bull3t Member
    Banned

    [C#] Global Variables.

    In any class (outside of a method), make sure you have a public static variable, and it will be global.
     
  7. Unread #4 - May 29, 2009 at 9:30 PM
  8. Darthatron
    Joined:
    May 22, 2006
    Posts:
    1,612
    Referrals:
    3
    Sythe Gold:
    0

    Darthatron Massive Troll
    Retired Sectional Moderator Visual Basic Programmers

    [C#] Global Variables.

    Please don't post in threads over 1 month old.
     
< How can I webbrowser control flat? | I need small help please :) >

Users viewing this thread
1 guest
Thread Status:
Not open for further replies.


 
 
Adblock breaks this site