I have developed certain financial and accounting packages on the basis of global variable which is I want to share. Here I present the small example of global variable which is communicated between multiple forms.
Form1 :-
Component require :-
1. ComboBox
2. Button
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Data.SqlClient;
namespace Globalvaribale
{
public partial class Form1 : Form
{
public static string name;
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
name = comboBox1.Text;
Form2 f2 = new Form2();
f2.Show();
}
private void Form1_Load(object sender, EventArgs e)
{
string connstr = "server=.;initial catalog=maa;uid=mah;pwd=mah";
SqlConnection con = new SqlConnection(connstr);
con.Open();
string sql = "select name from dummy";
SqlDataAdapter dap = new SqlDataAdapter(sql, con);
DataSet ds = new DataSet();
dap.Fill(ds);
comboBox1.DataSource = ds.Tables[0];
comboBox1.DisplayMember = "name";
comboBox1.ValueMember = "name";
}
}
}
Form2
Component is Label1
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
namespace Globalvaribale
{
public partial class Form2 : Form
{
public Form2()
{
InitializeComponent();
}
private void Form2_Load(object sender, EventArgs e)
{
label1.Text = Form1.name;
}
}
}
And thus I have prepared all my project which is works very well and no compliant on it. Note that there is more than 50 winforms on each projects. But recently I have noticed: Global Variables Are Bad.
Some people call me “mad” to utilize this type of global variable. The above article suggests many disadvantages, and I am confused that if it is true, than how are my projects and applications successful without any errors or mistakes?