I am trying to modify (add or remove) items of a combobox while the form is already running, I tried the methode add this.comboBox1.Items.add("test2"); but it only add the item if it runs before Application.Run(form); .
Why it is not updating/adding the item in the combobox ?
Form1.designer.cs:
namespace WindowsFormsApp1
{
partial class Form1
{
private System.ComponentModel.IContainer components = null;
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region Windows Form Designer generated code
private void InitializeComponent()
{
this.comboBox1 = new System.Windows.Forms.ComboBox();
this.SuspendLayout();
//
// comboBox1
//
this.comboBox1.FormattingEnabled = true;
this.comboBox1.Items.AddRange(new object[] {
"test"});
this.comboBox1.Location = new System.Drawing.Point(422, 116);
this.comboBox1.Name = "comboBox1";
this.comboBox1.Size = new System.Drawing.Size(121, 24);
this.comboBox1.TabIndex = 0;
this.comboBox1.SelectedIndexChanged += new System.EventHandler(this.comboBox1_SelectedIndexChanged);
//
// Form1
//
this.AutoScaleDimensions = new System.Drawing.SizeF(8F, 16F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(800, 450);
this.Controls.Add(this.comboBox1);
this.Name = "Form1";
this.Text = "Form1";
this.ResumeLayout(false);
}
public void test() {
this.comboBox1.Items.add("test2");
}
#endregion
private System.Windows.Forms.ComboBox comboBox1;
}
}
Form1.cs:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace WindowsFormsApp1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
}
}
}
Program.cs:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace WindowsFormsApp1
{
static class Program
{
[STAThread]
static void Main()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Form1 form = new Form1();
Application.Run(form);
form.test();
}
}
}
EDIT
How to achieve a periodical update of items by a function?
Instead of using SelectIndexChanged, you should use the click event
In this example I use a button to add an combobox item eveytime I click on it
might not be the best approach but it works fine
List<string> itemList = new List<string>();
int i=0;
private void button1_Click(object sender, EventArgs e)
{
i++;
itemList.Add("Test N° "+i);
}
private void comboBox1_Click(object sender, EventArgs e)
{
comboBox1.Items.Clear();
foreach(string item in itemList)
{
comboBox1.Items.Add(item);
}
}
And your programm isn't well made, Form1.cs.designer is use to create the UI (User Interface) of your programm, you MUST NOT add your function here.
FormX.cs.designer = UI, design
FormX.cs = functions
Programm.cs = defined which FormX.cs will run first (new(Form1))
You can also use it to add item with a function
Example :
public Form1()
{
InitializeComponent();
AddTenItems();
}
List<string> itemList = new List<string>();
int i=0;
private void button1_Click(object sender, EventArgs e)
{
itemList.Add("Test N° "+i);
i++;
}
private void AddTenItems()
{
for(int i=0; i<10; i++)
{
itemList.Add("Added N°" + i);
}
}
private void comboBox1_Click(object sender, EventArgs e)
{
comboBox1.Items.Clear();
foreach(string item in itemList)
{
comboBox1.Items.Add(item);
}
}
I have found a very helpful feature which is timers.
I have used a timer initialized inside the form constructor in order to update periodically the combobox, in the following example it added an item which is current time to the dropbox every 2 seconds for 5 times:
Form1.Designer.cs:
namespace WindowsFormsApp1
{
partial class Form1
{
private System.ComponentModel.IContainer components = null;
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
private void InitializeComponent()
{
this.comboBox1 = new System.Windows.Forms.ComboBox();
this.timer1 = new System.Windows.Forms.Timer();
this.SuspendLayout();
//
// comboBox1
//
this.comboBox1.FormattingEnabled = true;
this.comboBox1.Items.AddRange(new object[] {
"test"});
this.comboBox1.Location = new System.Drawing.Point(422, 116);
this.comboBox1.Name = "comboBox1";
this.comboBox1.Size = new System.Drawing.Size(121, 24);
this.comboBox1.TabIndex = 0;
this.comboBox1.SelectedIndexChanged += new System.EventHandler(this.comboBox1_SelectedIndexChanged);
//
// Form1
//
this.AutoScaleDimensions = new System.Drawing.SizeF(8F, 16F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(800, 450);
this.Controls.Add(this.comboBox1);
this.Name = "Form1";
this.Text = "Form1";
this.ResumeLayout(false);
}
#endregion
private System.Windows.Forms.ComboBox comboBox1;
private System.Windows.Forms.Timer timer1;
}
}
Form1.cs
namespace WindowsFormsApp1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
InitializeTimer();
}
private void InitializeTimer()
{
counter = 0;
timer1.Interval = 2000;
timer1.Enabled = true;
this.timer1.Tick += new System.EventHandler(this.timer1_Tick);
}
private void timer1_Tick(object sender, System.EventArgs e)
{
if (counter >= 5)
{
// Exit loop code.
timer1.Enabled = false;
counter = 0;
}
else
{
// Run your procedure here.
// Increment counter.
counter = counter + 1;
this.comboBox1.Items.Add(DateTime.Now.ToString("h:mm:ss tt"));
}
}
Related
I can't get the value from the first main form to the second form. I would like to be able to show the calculated number of folders and files in the second form in the richtextbox. I beg you to help me. Thank you to everyone for their advice.
Form1:
using System;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Windows.Forms;
namespace pocetadresaru
{
public partial class Form1 : Form
{
private Form2 form2;
public Form1()
{
InitializeComponent();
}
private void Form1_Shown(object sender, EventArgs e)
{
form2 = new Form2();
form2.FormClosed += new FormClosedEventHandler(form2_FormClosed);
form2.Location = new Point(Location.X, Location.Y + Height + 80);
form2.Show();
textBox1.Focus();
}
private void form2_FormClosed(object sender, FormClosedEventArgs e)
{
Close();
}
private void button1_Click_1(object sender, EventArgs e)
{
string folderPath= String.Empty;
var folder = new FolderBrowserDialog();
if (folder.ShowDialog() == DialogResult.OK)
{
folderPath = Path.GetFullPath(folder.SelectedPath);
textBox1.Text = folderPath;
}
}
public static int GetDirectoryCount(string folderPath)
{
return Directory.EnumerateDirectories(folderPath).Count();
}
public static int GetFileCount(string folderPath)
{
return Directory.EnumerateFiles(folderPath).Count();
}
}
}
Form2:
using System;
using System.Windows.Forms;
namespace pocetadresaru
{
public partial class Form2 : Form
{
public string Data
{
get { return richTextBox1.Text; }
set { richTextBox1.Text = "Adresář:" +
**the number of directories listed here** `+ Environment.NewLine + "Soubor:" +` **the number of files listed here**`; }
}
public Form2()
{
InitializeComponent();
}
}
}
Or if you really want to refresh the second form on click :
private void button1_Click(object sender, EventArgs e)
{
string folderPath = String.Empty;
var folder = new FolderBrowserDialog();
if (folder.ShowDialog() == DialogResult.OK)
{
folderPath = Path.GetFullPath(folder.SelectedPath);
textBox1.Text = folderPath;
form2.RefreshView(
GetDirectoryCount(folderPath),
GetFileCount(folderPath));
}
}
and in Form2 :
public string Data
{
get { return richTextBox1.Text; }
set
{
richTextBox1.Text = value ;
}
}
public void RefreshView(int dirCount, int filesCount)
{
Data = $"Adresář: {dirCount} directories, {filesCount} files";
}
Worked for me like that. (Only doing the setting of the directory count)
Form1
using System;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Windows.Forms;
namespace WindowsFormsApp1
{
public partial class Form1 : Form
{
private Form2 form2;
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
string folderPath = String.Empty;
var folder = new FolderBrowserDialog();
if (folder.ShowDialog() == DialogResult.OK)
{
folderPath = Path.GetFullPath(folder.SelectedPath);
var count = GetDirectoryCount(folderPath);
form2.Data = count.ToString();
}
}
public static int GetDirectoryCount(string folderPath)
{
return Directory.EnumerateDirectories(folderPath).Count();
}
private void Form1_Shown(object sender, EventArgs e)
{
form2 = new Form2();
form2.Location = new Point(Location.X, Location.Y + Height + 80);
form2.Show();
}
}
}
Form2
using System.Windows.Forms;
namespace WindowsFormsApp1
{
public partial class Form2 : Form
{
private string _data;
public string Data
{
get { return _data; }
set
{
_data = value;
textBox1.Text = _data;
}
}
public Form2()
{
InitializeComponent();
}
}
}
Experts
I would like to shuffle windows forms automatically every after 5 mins. windows forms contains Multiple querys , Multiple videos, Multiple powerpoints.
I am having three windows forms, as follows.
Forms 1 code :
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace Daily_System {
public partial class Form1: Form {
public Form1() {
InitializeComponent();
timer1.Enabled = true;
timer1.Interval = 5000;
timer1.Tick += timer1_Tick;
timer1.Start();
}
private void Form1_Load(object sender, EventArgs e) {
this.WindowState = FormWindowState.Maximized;
CenterToScreen();
}
private Timer timer1 = new Timer();
private void button1_Click_1(object sender, EventArgs e) {
this.WindowState = FormWindowState.Minimized;
Form2 f = new Form2(); // This is bad
timer2.Enabled = true;
}
private void timer2_Tick(object sender, EventArgs e) {
button1.PerformClick();
}
}
}
Forms 2: Microsoft Powerpoint file
multiple powerpoint files from network folder(path)
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using PowerPoint = Microsoft.Office.Interop.PowerPoint;
using Core = Microsoft.Office.Core;
namespace Daily_System {
public partial class Form2: Form {
public Form2() {
InitializeComponent();
this.WindowState = FormWindowState.Minimized;
timer1.Enabled = true;
timer1.Interval = 15000;
timer1.Start();
}
private void Tick(object sender, EventArgs e) {
Form3 Next = new Form3();
Next.Show();
this.Hide();
timer1.Stop(); //Stop timer after tick once
}
protected override void OnLoad(EventArgs e)
{
base.OnLoad(e);
this.BeginInvoke(new MethodInvoker(delegate() {
button1.PerformClick();
}));
}
private void button1_Click(object sender, EventArgs e) {
Microsoft.Office.Interop.PowerPoint.Application pptApp = new Microsoft.Office.Interop.PowerPoint.Application();
Microsoft.Office.Core.MsoTriState ofalse = Microsoft.Office.Core.MsoTriState.msoFalse;
Microsoft.Office.Core.MsoTriState otrue = Microsoft.Office.Core.MsoTriState.msoTrue;
pptApp.Visible = otrue;
pptApp.Activate();
Microsoft.Office.Interop.PowerPoint.Presentations ps = pptApp.Presentations;
var opApp = new Microsoft.Office.Interop.PowerPoint.Application();
pptApp.SlideShowEnd += PpApp_SlideShowEnd;
var ppPresentation = ps.Open(# "C:\Users\ok\Downloads\Parks-WASD2017.pptx", ofalse, ofalse, otrue);
var settings = ppPresentation.SlideShowSettings;
settings.Run();
}
private void PpApp_SlideShowEnd(Microsoft.Office.Interop.PowerPoint.Presentation Pres) {
Pres.Saved = Microsoft.Office.Core.MsoTriState.msoTrue;
Pres.Close();
}
private void Form2_Load(object sender, EventArgs e) {
}
private void button2_Click(object sender, EventArgs e) {
this.WindowState = FormWindowState.Minimized;
Form3 f = new Form3(); // This is bad
f.Show(); /// f.Show();
timer1.Enabled = true;
this.Hide();
timer1.Stop(); //Stop timer after tick once
}
private void timer1_Tick_1(object sender, EventArgs e) {
button2.PerformClick();
}
}
}
Forms 3: Multiple video files (MP4,FLV,MOV,etc)
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace Daily_System {
public partial class Form3: Form {
public Form3() {
InitializeComponent();
timer1.Enabled = true;
timer1.Interval = 15000;
timer1.Start();
}
private void Form3_Load(object sender, EventArgs e) {
axWindowsMediaPlayer1.settings.autoStart = true;
}
private void axWindowsMediaPlayer1_Enter_1(object sender, EventArgs e) {
axWindowsMediaPlayer1.URL = # "C:\Users\ok\Downloads\ok.mp4";
}
private void button1_Click(object sender, EventArgs e) {
this.WindowState = FormWindowState.Minimized;
Form1 f = new Form1(); // This is bad
f.Show(); /// f.Show();
timer1.Enabled = true;
this.Hide();
timer1.Stop(); //Stop timer after tick once
}
private void timer1_Tick_1(object sender, EventArgs e) {
button1.PerformClick();
}
}
}
Multiple video files from network folder(Path)
Requirement:
Each forms should change and display every after 5 min.
example : first form1 should display then after 5 mins form1 should minimized and form2 should show the slideshow and then after 5 mins form2 should minimized and form3 should play the video and then after 5 mins form3 should minimized and pause the video then form1 should display.
It should keep doing the same steps as above.
Final condition: All forms should stop exactly at 6 pm(Everyday) and it should start automatically at 7 am (Everyday).
Please advise...
One way is to create base class for forms to control minimizing and maximizing of them and also finding out when the specific form being minimized or maximized by overriding OnStart() and OnStop() methods. This can be done as follow:
Define new base class named CustomForm:
public class CustomForm : Form
{
public static List<CustomForm> AllForms = new List<CustomForm>();
private static int CurrentFormIndex = 0;
private static Timer SliderTimer = new Timer() { Interval = 5000 }; // { Interval = 5 * 60000 };
public static void Start(params CustomForm[] forms)
{
AllForms.AddRange(forms);
forms[0].Show();
forms[0].WindowState = FormWindowState.Maximized;
AllForms[0].OnStart(AllForms[0]);
SliderTimer.Tick += SliderTimer_Tick;
SliderTimer.Start();
}
private static void SliderTimer_Tick(object sender, EventArgs e)
{
SliderTimer.Stop();
// Minimizing current form
AllForms[CurrentFormIndex].OnStop(AllForms[CurrentFormIndex]);
AllForms[CurrentFormIndex].WindowState = FormWindowState.Minimized;
// Maximizing next form
int NextFormIndex = (CurrentFormIndex + 1) % AllForms.Count;
if (!AllForms[NextFormIndex].Visible)
AllForms[NextFormIndex].Show();
AllForms[NextFormIndex].WindowState = FormWindowState.Maximized;
AllForms[NextFormIndex].OnStart(AllForms[NextFormIndex]);
CurrentFormIndex = NextFormIndex;
SliderTimer.Start();
}
// Application will exits when one of forms being closed
protected override void OnFormClosed(FormClosedEventArgs e)
{
base.OnFormClosed(e);
Application.Exit();
}
// For overriding in forms to Start something such as playing or etc
protected virtual void OnStart(CustomForm Sender)
{
}
// For overriding in forms to Stop something such as playing or etc
protected virtual void OnStop(CustomForm Sender)
{
}
}
Change Program class as follow:
static class Program
{
[STAThread]
static void Main()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
CustomForm.Start(new Form1(), new Form2(), new Form3());
Application.Run();
}
}
Change your forms to inherit CustomForm instead of Form as follow:
public partial class Form1 : CustomForm
{
public Form1()
{
InitializeComponent();
}
private void Form1_Shown(object sender, EventArgs e)
{
// axWindowsMediaPlayer1.URL = #"C:\Users\ok\Downloads\ok.mp4";
WMPLib.IWMPMedia v1 = axWindowsMediaPlayer1.newMedia(#"d:\1.mp4");
axWindowsMediaPlayer1.currentPlaylist.appendItem(v1);
WMPLib.IWMPMedia v2 = axWindowsMediaPlayer1.newMedia(#"d:\2.mp4");
axWindowsMediaPlayer1.currentPlaylist.appendItem(v2);
WMPLib.IWMPMedia v3 = axWindowsMediaPlayer1.newMedia(#"d:\3.mp4");
axWindowsMediaPlayer1.currentPlaylist.appendItem(v3);
}
// To start playing video and etc when form being maximized
protected override void OnStart(CustomForm Sender)
{
axWindowsMediaPlayer1.Ctlcontrols.play();
}
// To stop playing video and etc when form being minimized
protected override void OnStop(CustomForm Sender)
{
axWindowsMediaPlayer1.Ctlcontrols.pause();
}
}
Form2:
public partial class Form2 : CustomForm
{
Microsoft.Office.Interop.PowerPoint.Presentation ppPresentation;
Microsoft.Office.Interop.PowerPoint.SlideShowSettings settings;
Microsoft.Office.Interop.PowerPoint.Application opApp;
int StartingSlide = 1;
public Form2()
{
InitializeComponent();
}
protected override void OnStart(CustomForm Sender)
{
Microsoft.Office.Interop.PowerPoint.Application pptApp = new Microsoft.Office.Interop.PowerPoint.Application();
Microsoft.Office.Core.MsoTriState ofalse = Microsoft.Office.Core.MsoTriState.msoFalse;
Microsoft.Office.Core.MsoTriState otrue = Microsoft.Office.Core.MsoTriState.msoTrue;
pptApp.Visible = otrue;
pptApp.Activate();
Microsoft.Office.Interop.PowerPoint.Presentations ps = pptApp.Presentations;
opApp = new Microsoft.Office.Interop.PowerPoint.Application();
opApp.SlideShowNextSlide += OpApp_SlideShowNextSlide;
ppPresentation = ps.Open(#"c:\a.pptx", ofalse, ofalse, otrue);
settings = ppPresentation.SlideShowSettings;
settings.RangeType = Microsoft.Office.Interop.PowerPoint.PpSlideShowRangeType.ppShowSlideRange;
settings.StartingSlide = StartingSlide;
settings.Run();
}
private void OpApp_SlideShowNextSlide(Microsoft.Office.Interop.PowerPoint.SlideShowWindow Wn)
{
StartingSlide = Wn.View.CurrentShowPosition;
}
protected override void OnStop(CustomForm Sender)
{
ppPresentation.Close();
//opApp.Quit();
Process.Start("cmd", "/c taskkill /im POWERPNT.EXE");
}
}
There are a lot of possible ways to do this. Winforms is a Lego box and lets you snap the pieces together any way you want. Deriving your own class from one of the built-in winforms classes is a basic strategy. What you need is a little controller that takes care of the form switching. Best kind of class to override is ApplicationContext. The default one you get is a very simple one that merely ensures that the main form is shown and terminates the app when you close it.
Let's derive our own. This is a potentially heavy-weight app, these are not cheap forms. So we want to specify the forms to switch by their Type instead of their instance, creating and destroying them when the forms gets switched. You'll want the app to terminate whenever the current one is closed by the user. Copy/paste this code into the Program.cs file:
class FormSwitcher : ApplicationContext {
Timer switcher;
Type[] forms;
int formIndex;
Form currentForm;
bool switching;
public FormSwitcher(params Type[] forms) {
this.forms = forms;
switcher = new Timer() { Enabled = true };
switcher.Interval = System.Diagnostics.Debugger.IsAttached ? 3000 : 5 * 60000;
switcher.Tick += SwitchForm;
formIndex = -1;
SwitchForm(this, EventArgs.Empty);
}
private void SwitchForm(object sender, EventArgs e) {
switching = true;
formIndex += 1;
if (formIndex >= forms.Length) formIndex = 0;
var newform = (Form)Activator.CreateInstance(forms[formIndex]);
newform.FormClosed += delegate { if (!switching) this.ExitThread(); };
if (currentForm != null) {
newform.StartPosition = FormStartPosition.Manual;
newform.Bounds = currentForm.Bounds;
}
newform.Show();
if (currentForm != null) currentForm.Close();
currentForm = newform;
switching = false;
}
}
Hopefully it is obvious what it does, if not then let me know and I'll add comments. Now you can modify the Main() method in that same file, you pass an instance of this class to the Application.Run() method. I'll copy/paste the code I tested:
[STAThread]
static void Main() {
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new FormSwitcher(typeof(Form1), typeof(Form2)));
}
Here is sample code that creates the 3 forms, then every 5 seconds switches which is maximized (others are minimized). The application exits when any form is closed. I've put comments throughout, and following it is code you can use to pause playback on forms:
internal static class Program
{
/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]
private static void Main()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
//here we create our 3 forms. note, you can create and show as many as you want here
//the application will automatically loop through them
new Form1().Show();
new Form2().Show();
new Form().Show();
//minimize all forms, and set a close handler
foreach (Form form in Application.OpenForms)
{
form.WindowState = FormWindowState.Minimized;
form.FormClosed += Form_FormClosed;
}
//start a thread to manage switching them
Task.Run((Action)Go);
//start the main UI thread loop
Application.Run();
}
private static void Go()
{
while (true)
{
//loop through all forms
foreach (Form form in Application.OpenForms)
{
//show it (send execution to UI thread)
form.Invoke(new MethodInvoker(() =>
{
form.Show();
form.WindowState = FormWindowState.Maximized;
}));
//wait 5 seconds
Thread.Sleep(5000);
//minimize it (send execution to UI thread)
form.Invoke(new MethodInvoker(() =>
{
form.WindowState = FormWindowState.Minimized;
}));
}
}
}
private static void Form_FormClosed(object sender, FormClosedEventArgs e)
{
Application.Exit();
}
}
Now for forms that need to take action when minimized/maximized, add a Resize handler like this into the code on the form:
private void Form1_Resize(object sender, EventArgs e)
{
if (WindowState == FormWindowState.Minimized)
{
//stop any playback
} else
{
//start any playback
}
}
This is my form1 which I designed. When I type emp id in form1's textbox and click on the search button it shows form2.
In this second form I need to carry all the details corresponding to emp id and should display details into corresponding textboxes.
I have created emp table in SQL Server...I would like to pull the employee details from the database based on emp id. This is my code:
form1:
private void btnsearch_Click(object sender, EventArgs e)
{
Form2 f2 = new Form2(tbempid.Text);
f2.Show();
SqlConnection con = new SqlConnection("Data Source=RAJIM-PC;Initial Catalog=Practicing;User ID=sa;Password=RajiSha");
try
{
con.Open();
SqlCommand com = new SqlCommand("SELECT eid,emp_name,mobile_no FROM emp WHERE ID='" + tbempid.Text.Trim() + "'", con);
com.CommandType = CommandType.Text;
DataTable dtb = new DataTable();
SqlDataAdapter da = new SqlDataAdapter(com);
da.Fill(dtb);
if (dtb.Rows.Count > 0)
{
Form2.txtempid.Text= dtb.Rows[0]["eid"].ToString();
Form2.txtempname.Text = dtb.Rows[0]["emp_name"].ToString();
Form2.txtmbno.Text= dtb.Rows[0]["mobile_no"].ToString();
}
FormCollection fc = System.Windows.Forms.Application.OpenForms;
foreach (Form f in fc)
{
if (f.Name == "Form2")
{
f.Update();
}
}
}
catch (SqlException sql)
{
System.Windows.Forms.MessageBox.Show(sql.Message);
}
finally
{
if (con.State == ConnectionState.Open)
{
con.Close();
con.Dispose();
}
}
}
form2:
public partial class Form2 : Form
{
public static string txtempid;
public static string txtempname;
public static string txtmbno;
public Form2(string strtxtbox)
{
InitializeComponent();
tbempid.Text = strtxtbox;
}
}
Looks like your doing all the work for filling out Form2 in Form1, I would suggest moving the code into Form2 and calling it from the Form2's constructor. Not only will this make more sense, but means you will only hit your database once to get the results.
Alternatively, you could pass Form2 your data table from Form1 and use the values in Form2's constructor. Again, saving a second query going to the database.
You can take constructor of form 2 as shown below :-
public Form2(string txtempid, string txtempname, string txtmbno)
{
InitializeComponent();
txtempid.Text = txtempid;
txtempname.Text = txtempname;
txtmbno.Text = txtmbno;
}
and in form 1 :-
var form2 = new Form2(dtb.Rows[0]["eid"].ToString(), dtb.Rows[0]["emp_name"].ToString(), dtb.Rows[0]["mobile_no"].ToString());
You should change Form2 to f2 here:
Form2.txtempid.Text= dtb.Rows[0]["eid"].ToString();
Form2.txtempname.Text = dtb.Rows[0]["emp_name"].ToString();
Form2.txtmbno.Text= dtb.Rows[0]["mobile_no"].ToString();
So it becomes:
f2.txtempid.Text= dtb.Rows[0]["eid"].ToString();
f2.txtempname.Text = dtb.Rows[0]["emp_name"].ToString();
f2.txtmbno.Text= dtb.Rows[0]["mobile_no"].ToString();
Update 1
You are trying to assign those fields to the string variables. However, what you should do is to assign them to relevant textbox controls like this:
Assume you have 3 textboxes named tbempid, tbempname, tbmbno on Form2
f2.tbempid.Text= dtb.Rows[0]["eid"].ToString();
f2.tbempname.Text = dtb.Rows[0]["emp_name"].ToString();
f2.tbmbno.Text= dtb.Rows[0]["mobile_no"].ToString();
Update 2
Due to the protection level, you need to add a function in Form2:
public void SetTextBoxes(string strempid, string strempname, string strmbno)
{
tbempid.Text = strempid;
tbempname.Text = strempname;
tbmbno.Text = strmbno;
}
And change the 3 lines to:
f2.SetTextBoxes(dtb.Rows[0]["eid"].ToString(), dtb.Rows[0]["emp_name"].ToString(), dtb.Rows[0]["mobile_no"].ToString());
The following is a very quick example that I've thrown together of what I suggested above. It does not follow best practice for purposes of simplicity. The areas to concentrate on below is the EmployeeModel class, Form1 and Form2 source.
The idea here is utilize the EmployeeModel class as a container that both forms have access to.
Form 1 acquires the employee information. (Keep in mind, the model class can contain any information you like. It does not have to be reserved for just properties. If you prefer, you can keep a reference to a dataset here.)
Form 2 has a reference to this EmployeeModel class. When the button click event is fired on form1, a new EmployeeModel class object is created and initialized with the relevant information that would be displayed in form2. It is then passed as an object reference using Form2's overloaded constructor.
On the Onload event of Form2, the label.Text properties are initialized with what is contained in the EmployeeModel that was passed as a reference.
This is a very basic implementation and in most real world applications where expandability and maintainability are also factors to consider, a MVP or MVVM WinForms architectural framework is typically used.
Form 1 designer:
namespace FormToFormExample
{
partial class Form1
{
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// Clean up any resources being used.
/// </summary>
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
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 InitializeComponent()
{
this.textBox1 = new System.Windows.Forms.TextBox();
this.button1 = new System.Windows.Forms.Button();
this.SuspendLayout();
//
// textBox1
//
this.textBox1.Location = new System.Drawing.Point(12, 12);
this.textBox1.Name = "textBox1";
this.textBox1.Size = new System.Drawing.Size(260, 20);
this.textBox1.TabIndex = 0;
//
// button1
//
this.button1.Location = new System.Drawing.Point(197, 64);
this.button1.Name = "button1";
this.button1.Size = new System.Drawing.Size(75, 23);
this.button1.TabIndex = 2;
this.button1.Text = "button1";
this.button1.UseVisualStyleBackColor = true;
//
// Form1
//
this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(284, 100);
this.Controls.Add(this.button1);
this.Controls.Add(this.textBox1);
this.Name = "Form1";
this.Text = "Form1";
this.ResumeLayout(false);
this.PerformLayout();
}
#endregion
private System.Windows.Forms.TextBox textBox1;
private System.Windows.Forms.Button button1;
}
}
Form 2 designer:
namespace FormToFormExample
{
partial class Form2
{
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// Clean up any resources being used.
/// </summary>
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
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 InitializeComponent()
{
this.label1 = new System.Windows.Forms.Label();
this.label2 = new System.Windows.Forms.Label();
this.SuspendLayout();
//
// label1
//
this.label1.AutoSize = true;
this.label1.Location = new System.Drawing.Point(12, 9);
this.label1.Name = "label1";
this.label1.Size = new System.Drawing.Size(35, 13);
this.label1.TabIndex = 0;
this.label1.Text = "label1";
//
// label2
//
this.label2.AutoSize = true;
this.label2.Location = new System.Drawing.Point(12, 34);
this.label2.Name = "label2";
this.label2.Size = new System.Drawing.Size(35, 13);
this.label2.TabIndex = 1;
this.label2.Text = "label2";
//
// Form2
//
this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(284, 262);
this.Controls.Add(this.label2);
this.Controls.Add(this.label1);
this.Name = "Form2";
this.Text = "Form2";
this.ResumeLayout(false);
this.PerformLayout();
}
#endregion
private System.Windows.Forms.Label label1;
private System.Windows.Forms.Label label2;
}
}
Model class:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace FormToFormExample
{
public class EmployeeModel
{
#region Properties
private Guid _employeeID;
public Guid EmployeeID
{
get { return this._employeeID; }
set { this._employeeID = value; }
}
private string _name;
public string Name
{
get { return this._name; }
set { this._name = value; }
}
#endregion
#region Constructors
public EmployeeModel()
{
this._employeeID = Guid.NewGuid();
}
public EmployeeModel(string name)
: this()
{
this._name = name;
}
#endregion
}
}
Form 1 source:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace FormToFormExample
{
public partial class Form1 : Form
{
#region Constructors
public Form1()
{
InitializeComponent();
Initialize();
BindComponents();
}
#endregion
#region Methods
private void BindComponents()
{
this.button1.Click += button1_Click;
}
private void Initialize()
{
this.textBox1.Text = string.Empty;
}
#endregion
#region Events
void button1_Click(object sender, EventArgs e)
{
Form2 form2 = new Form2(new EmployeeModel(textBox1.Text));
form2.ShowDialog();
Initialize();
}
#endregion
}
}
Form 2 source:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace FormToFormExample
{
public partial class Form2 : Form
{
EmployeeModel _model;
#region Constructors
public Form2()
{
InitializeComponent();
BindComponents();
}
public Form2(EmployeeModel model)
: this()
{
this._model = model;
}
#endregion
#region Methods
private void BindComponents()
{
this.Load += Form2_Load;
}
private void Initialize()
{
this.label1.Text = this._model.EmployeeID.ToString();
this.label2.Text = this._model.Name;
}
#endregion
#region Events
void Form2_Load(object sender, EventArgs e)
{
Initialize();
}
#endregion
}
}
Program:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace FormToFormExample
{
static class Program
{
/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]
static void Main()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new Form1());
}
}
}
"Give the code below, how would I access the listBox1 in Form2? I'm sure I'm missing stupid! Thanks in advance."
Error 1 'WindowsFormsApplication1.Form2.listBox1' is inaccessible due
to its protection
level C:\Users\dugaj0\Desktop\Developing\GlobalUser\WindowsFormsApplication1\WindowsFormsApplication1\Form1.cs 24 19 WindowsFormsApplication1
using System;
using System.IO;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace WindowsFormsApplication1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
String value1 = File.ReadAllText(textBox1.Text);
foreach (string line in value1.Split('\n'));
Form2.listBox1.Items.Add();
}
}
}
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;
namespace WindowsFormsApplication1
{
public partial class Form2 : Form
{
public Form2()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
Application.Exit();
}
}
}
namespace WindowsFormsApplication1
{
partial class Form2
{
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// Clean up any resources being used.
/// </summary>
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
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 InitializeComponent()
{
this.listBox1 = new System.Windows.Forms.ListBox();
this.button1 = new System.Windows.Forms.Button();
this.SuspendLayout();
//
// listBox1
//
this.listBox1.FormattingEnabled = true;
this.listBox1.Location = new System.Drawing.Point(13, 13);
this.listBox1.Name = "listBox1";
this.listBox1.Size = new System.Drawing.Size(259, 212);
this.listBox1.TabIndex = 0;
//
// button1
//
this.button1.Location = new System.Drawing.Point(105, 231);
this.button1.Name = "button1";
this.button1.Size = new System.Drawing.Size(75, 23);
this.button1.TabIndex = 1;
this.button1.Text = "Exit";
this.button1.UseVisualStyleBackColor = true;
this.button1.Click += new System.EventHandler(this.button1_Click);
//
// Form2
//
this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(284, 262);
this.Controls.Add(this.button1);
this.Controls.Add(this.listBox1);
this.Name = "Form2";
this.Text = "Form2";
this.ResumeLayout(false);
}
#endregion
private System.Windows.Forms.ListBox listBox1;
private System.Windows.Forms.Button button1;
}
}
First of all you have to create an instance of Form2.
namespace WindowsFormsApplication1
{
public partial class Form1 : Form
{
private Form2 form2;
public Form1()
{
InitializeComponent();
form2 = new Form2();
}
private void button1_Click(object sender, EventArgs e)
{
String value1 = File.ReadAllText(textBox1.Text);
foreach (string line in value1.Split('\n'))
{
form2.listBox1.Items.Add(line);
}
}
}
}
Your specific error is because of listBox1 is being private. Change it to public and you can access it.
public System.Windows.Forms.ListBox listBox1;
Also since you already have:
using System.Windows.Forms;
You can write
public ListBox listBox1;
I created a default form in Visual Studio 2010 and on the form design I have not changed anything. I only added following code in Form1.cs:
using System;
using System.Windows.Forms;
namespace WinFormTest1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
this.TopMost = true;
this.ShowInTaskbar = true;
this.Load += new EventHandler(Form1_Load);
this.Shown += new EventHandler(Form1_Shown);
}
void Form1_Load(object sender, EventArgs e)
{
this.Opacity = 0;
}
void Form1_Shown(object sender, EventArgs e)
{
this.Opacity = 1;
}
}
}
Starting this program the form does not appear on the taskbar. It only appears on the task bar when made active any other window, and then activating this form.
What is the reason of such behavior?
Edited:
Why do I need to set the opacity of it in handler Form1_Load?
I created class FormAppearingEffect whose code below:
using System;
using System.Diagnostics;
using System.Threading;
using System.Windows.Forms;
namespace AG.FormAdditions
{
public class FormAppearingEffect
{
private Form form;
double originalOpacity;
public FormAppearingEffect(Form form)
{
this.form = form;
form.Load += form_Load;
form.Shown += form_Shown;
}
void form_Load(object sender, EventArgs e)
{
originalOpacity = form.Opacity;
form.Opacity = 0;
}
private void form_Shown(object sender, EventArgs e)
{
try
{
double currentOpacity = 0;
form.Opacity = currentOpacity;
Stopwatch stopwatch = new Stopwatch();
stopwatch.Start();
for (int i = 1; currentOpacity < originalOpacity; i++)
{
currentOpacity = 0.1 * i;
form.Opacity = currentOpacity;
Application.DoEvents();
//if processor loaded and does not have enough time for drawing form, then skip certain count of steps
int waitMiliseconds = (int)(50 * i - stopwatch.ElapsedMilliseconds);
if (waitMiliseconds >= 0)
Thread.Sleep(waitMiliseconds);
else
i -= waitMiliseconds / 50 - 1;
}
stopwatch.Stop();
form.Opacity = originalOpacity;
}
catch (ObjectDisposedException) { }
}
}
}
In any form of program I use this class like this:
using System;
using System.Windows.Forms;
using AG.FormAdditions;
namespace WinFormTest1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
FormAppearingEffect frmEffects = new FormAppearingEffect(this);
}
}
}
Thus my form appears on the screen "gradually".
This is where I found a bug, which we are in this topic.
And that's it for this reason I need to set the opacity in the event handlers.