I write code to add UserControl in Form:
UserControl edt = new UserControl();
edt.Name = "ItemEdit";
frm_Editor frm = new frm_Editor();
frm.Controls.Add(edt);
frm.Show();
And then, I find UserControl in Form:
Control[] tbxs = this.Controls.Find("ItemEdit", true);
if (tbxs != null && tbxs.Length > 0)
{
MessageBox.Show("Found");
}
But the result is null && tbxs.Length = 0
Please guide me solutions to process problems. Thanks so much!
It works in this small program, and it might point you towards a solution with your own code.
using System;
using System.Windows.Forms;
namespace FormTest
{
static class Program
{
/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]
static void Main()
{
Form1 frm = new Form1();
UserControl edt = new UserControl();
edt.Name = "ItemEdit";
frm.Controls.Add(edt);
Application.Run(frm);
}
}
}
using System.Windows.Forms;
namespace FormTest
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, System.EventArgs e)
{
Control[] tbxs = this.Controls.Find("ItemEdit", true);
if (tbxs != null && tbxs.Length > 0)
{
MessageBox.Show("Found");
}
}
}
}
Related
I have 3 forms: manager_dashboard, staff_details, and staff_registration. I have connected the staff details form using a panel in the manager dashboard. Now I want to open a new form when I click a button inside staff details in the manager dashboard panel.
Manager_Dashboard md = new Manager_Dashboard();
Delete_Satff ds = new Delete_Satff();
ds.TopLevel = false;
md.pnl_view.Controls.Add(ds);
ds.BringToFront();
ds.Show();
You just need to define a public method in the child window and call it in the main window.
See the code below for details:
Form1:
using System;
using System.Windows.Forms;
namespace WinFormsApp1
{
public partial class Form1 : Form
{
Form2 form2 = new Form2();
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
form2.Show();
}
private void button2_Click(object sender, EventArgs e)
{
form2.OpenFomr3();
}
}
}
Form2:
using System;
using System.Windows.Forms;
namespace WinFormsApp1
{
public partial class Form2 : Form
{
public void OpenFomr3()
{
Form3 form3 = new Form3();
form3.TopLevel = false;
form3.Dock = System.Windows.Forms.DockStyle.Fill;
this.panel1.Controls.Add(form3);
form3.Show();
}
public Form2()
{
InitializeComponent();
}
}
}
OutPut:
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();
}
}
}
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.
i have a main form name fmMain
black mark is show browse file path to datagridview
and red mark is show form to datagridview.
i try to send path to datagridview and succes. here is the code
namespace tstIniF
{
public partial class fmMain : Form
{
string ConfigFileName = "app.cfg";
CFileConfig cFileConfig;
public fmMain()
{
InitializeComponent();
cFileConfig = new CFileConfig();
}
private void btnQuit_Click(object sender, EventArgs e)
{
Close();
}
private void btnDirectort_Click(object sender, EventArgs e)
{
if (dlgFolder.ShowDialog() != DialogResult.OK) return;
string s = dlgFolder.SelectedPath;
txtDirectory.Text = s;
/*p = (string)dgvConfigFile.Rows[idx++].Cells[1].Value; cFileConfig.cfgContourFile = p;
p = (string)dgvConfigFile.Rows[idx++].Cells[1].Value; cFileConfig.cfgConnectionString = p;*/
}
private void btnDirectBase_Click(object sender, EventArgs e)
{
if (dlgFile.ShowDialog() != DialogResult.OK) return;
string s = dlgFile.FileName;
int idx = 0;
dgvConfigFile.Rows[idx++].Cells[1].Value = cFileConfig.cfgBaseMapFile = s;
}
private void btnDirectCont_Click(object sender, EventArgs e)
{
if (dlgFile.ShowDialog() != DialogResult.OK) return;
string s = dlgFile.FileName;
int idx = 1;
dgvConfigFile.Rows[idx++].Cells[1].Value = cFileConfig.cfgContourFile = s;
}
private void btnDirectConn_Click(object sender, EventArgs e)
{
fConn op = new fConn();
op.ShowDialog();
}
}
}
red mark as btnDirectConn i show new form like this
and here is my form fConn
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 tstIniF
{
public partial class fConn : Form
{
public fConn()
{
InitializeComponent();
}
private void btnSave_Click(object sender, EventArgs e)
{
if (txtServ.Text.Trim() == "" || txtDb.Text.Trim() == "" || txtUid.Text.Trim() == "" || txtPwd.Text.Trim() == "")
{
MessageBox.Show("Mohon diisi semua field....");
}
else
{
//string textAll = this.txtServ.Text + this.txtDb.Text + this.txtUid.Text + this.txtPwd.Text;
fmMain frm = new fmMain();
frm._textBox = _textBox1;
this.Close();
//Close();
//frm.Show();
}
}
public string _textBox1
{
get { return txtServ.Text + txtDb.Text; }
}
}
}
the question is how to show data in form fConn to fmMain datagridview , i fill the fConn entry and close and back to fmMain so the result is
I would use delegate to handle this,
change fConnform as below
public partial class fConn : Form
{
public SaveDelegate SaveCallback;
public fConn()
{
InitializeComponent();
}
public void btnSave_Click(object sender, EventArgs e)
{
SaveCallback("set text what you need to send to main form here...");
}
}
And fmMain as below
public delegate void SaveDelegate(string text);
public partial class fmMain
{
public fmMain()
{
InitializeComponent();
}
private void btnDirectConn_Click(object sender, EventArgs e)
{
fConn op = new fConn();
op.SaveCallback += new SaveDelegate(this.SavemCallback);
op.ShowDialog();
}
private void SavemCallback(string text)
{
// you have text from fConn here ....
}
In the frmMain declare the fConn form at the class level so that it won't get disposed when the form closes. Now the frmMain can access any public objects in fConn.
Don't re-declare frmMain in fConn. Use _textBox = op._textBox1 right after op.ShowDialog();
My application currently has 2 forms. It creates a sub form, Form2, which ends with the following code:
public partial class Form2 : Form
{ ...
Form1 frm = new Form1();
frm.rglu = glu;
frm.rdate = fulldate;
frm.sort();
Close();
}
Note that form1 is just a couple of buttons at the moment. One starts off Form2 as follows:
private void button2_Click(object sender, EventArgs e)
{
using (Form2 AcqForm = new Form2())
{
AcqForm.ShowDialog(this);
}
}
No other code runs except a button test(); shown later).
This frm.sort(); runs the following code found in Form1:
public partial class Form1 : Form
{
public void sort()
{
datelist = new List<DateTime>(rdate);
datelist.Sort((a, b) => a.CompareTo(b));
var result = rdate
.Select((d, i) => new { Date = d, Int = rglu[i] })
.OrderBy(o => o.Date)
.ToArray();
this.rdate = result.Select(o => o.Date).ToArray();
this.rglu = result.Select(o => o.Int).ToArray(); //all works fine
for (int i = 7; i+7 <= rglu.Length; i++)
{
Console.WriteLine(Convert.ToString(rdate[i]) + Convert.ToString(rglu[i]));
} //This shows values as expected
}
}
However when I set a button to run some more code using rglu and rdate the I get null pointer errors:
public partial class Form1 : Form
{
private void test(object sender, EventArgs e)
{
for (int i = 7; i < rglu.Length; i++){} //rglu is null! The values are lost.
}
}
I believe the solution requires a int[] rglu {get; set;} method. However so far I have been unsuccessful in using these things at all. Has anyone encountered this problem?
Edit:
rglu is defined like this:
public int[] rglu { get; set; } //I don't get how this works though
Problem is in form2,
You mustn't write 'Form1 frm = new Form1();' this code.
in Form1 wite code like this:
using System;
using System.Collections.Generic;
using System.Windows.Forms;
namespace WindowsFormsApplication2
{
public partial class Form1 : Form
{
public int rglu;
public DateTime rdate;
public Form1()
{
InitializeComponent();
}
private void btnShowForm2_Click(object sender, EventArgs e)
{
Form2 frm2=new Form2();
frm2.Form1Instance = this;
frm2.Show();
}
public void sort()
{
datelist = new List<DateTime>(rdate);
datelist.Sort((a, b) => a.CompareTo(b));
var result = rdate
.Select((d, i) => new { Date = d, Int = rglu[i] })
.OrderBy(o => o.Date) // Sort by whatever field you want
.ToArray();
this.rdate = result.Select(o => o.Date).ToArray();
this.rglu = result.Select(o => o.Int).ToArray(); //all works fine
for (int i = 7; i + 7 <= rglu.Length; i++)
{
Console.WriteLine(Convert.ToString(rdate[i]) + Convert.ToString(rglu[i]));
} //This returns values as expected
}
}
}
in Form2 write codes like this:
using System;
using System.Windows.Forms;
namespace WindowsFormsApplication2
{
public partial class Form2 : Form
{
public Form1 Form1Instance;
public Form2()
{
InitializeComponent();
}
private void btnSortValues_Click(object sender, EventArgs e)
{
Form1Instance.rglu = glu;
Form1Instance.rdate = fulldate;
Form1Instance.sort();
Close();
}
}
}
Purely from a defensive coding style point of view I think it would be good practice to test for rglu being null before calling methods on it.
e.g.
public void test()
{
if(rglu == null)
{
throw new InvalidOperationException("rglu is null!");
}
for (int i = 7; i < rglu.Length; i++){} //rglu is not null!
}
I'd also question why test() needs to be public if it's called from a button click event.
Form1 frm = new Form1();
frm.rglu = glu;
frm.rdate = fulldate;
frm.sort();
Close();
You don't use frm variable anywhere else and don't display the form, so garbage collectior is the only one who is going to receive that data in rdate and rglu variables in this case.
It seems like you wanted to operate on already existing form. In this case you must pass a reference to existing Form1 to your method in Form2.
Update:
It may look like this:
public partial class Form2 : Form
{
// ...
private readonly Form1 _parent;
public Form2(Form1 parent) : this()
{
_parent = parent;
}
// ... somewhere in a method which closes Form2:
Form1 frm = _parent;
frm.rglu = glu;
frm.rdate = fulldate;
frm.sort();
Close();
// ...
}
To show Form2 from Form1, use
using(var form2 = new Form2(this))
{
form2.ShowDialog(this);
}