Skip to content

Instantly share code, notes, and snippets.

@kyrathasoft
Created November 9, 2019 13:14
Show Gist options
  • Save kyrathasoft/121cef4479409309676290e2e7151856 to your computer and use it in GitHub Desktop.
Save kyrathasoft/121cef4479409309676290e2e7151856 to your computer and use it in GitHub Desktop.
Access and modify properties of textbox from within another class
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;
/*
Shows how we can access Form1's default TextBox (textBox1) from within another class, by passing into that
other class's constructor a refence to Form1. We create public properties for the form's 'textBox1' TextBox,
because the textbox is private to Form1 (see the declaration in Form1Designer.cs, which looks like this):
private System.Windows.Forms.TextBox textBox1;
By passing a reference to Form1 into the other class's constructor, and then utilizing the properties we
created, we can alter Form1's textbox's .Width and .Text properties from another class.
*/
namespace testApp {
public partial class Form1 : Form {
public Form1() {
InitializeComponent();
}
public string TextValue {
set { textBox1.Text = value; }
}
public int TextWidth {
set { textBox1.Width = value; }
}
private void button1_Click(object sender, EventArgs e) {
OtherClass oc = new OtherClass(this);
}
}
public class OtherClass{
Form1 f2;
public OtherClass(Form1 f) {
f2 = f;
f2.TextValue = "Hello World!";
f2.TextWidth = 200;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment