I am using Windows Form Application. I have created on form for listing and on Add button I have create new window. When new record is adding datasource is updating but gridview not displaying last added record. Why this is happening?
public MainForm()
{
InitializeComponent();
BindCompanyData();
}
public void BindCompanyData()
{
List<CompanyListModel> companyListModel = new List<CompanyListModel>();
companyListModel = _obiClient.GetCompanies();
companyDataGrid.DataSource = null;
companyDataGrid.DataSource = companyListModel;
companyDataGrid.Refresh();
companyDataGrid.CellClick += new DataGridViewCellEventHandler(DatGridCell_Click);
}
private void btn_addCompany_Click(object sender, EventArgs e)
{
CompanyAddEdit companyAddEdit = new CompanyAddEdit();
companyAddEdit.ShowForm();
}
On button add It open new form. and on close that form I have called BindCompanyData() method.
private void btn_save_Click(object sender, EventArgs e)
{
string selectedItem = cmbbx_companyType.SelectedItem.ToString();
WriteXML(selectedItem);
this.Close();
MainForm mainForm = new MainForm();
mainForm.BindCompanyData();
}
What is missing?
Your problem is you are running BindCompanyData(); on newly created form with your code:
MainForm mainForm = new MainForm();
mainForm.BindCompanyData();
What you should do is inside CompanyAddEdit constructor request for MainForm form parameter and pass your current form which you use in button. So your code look like this:
//Inside CompanyAddEdit form
class CompanyAddEdit : Form
{
MainForm passedForm;
public CompanyAddEdit(MainForm form)
{
this.passedForm = form;
}
//other code
private void btn_save_Click(object sender, EventArgs e)
{
string selectedItem = cmbbx_companyType.SelectedItem.ToString();
WriteXML(selectedItem);
this.Close();
passedForm.BindCompanyData();
}
}
//Inside main form
private void btn_addCompany_Click(object sender, EventArgs e)
{
CompanyAddEdit companyAddEdit = new CompanyAddEdit(this);
companyAddEdit.ShowForm();
}
Related
I have two forms. The main form contains a treeview. After I show the second form, the treeview loses focus. That's okay, but I want to activate the treeview when the second form closes.
Form1.cs
namespace ex
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
using (Form2 form2 = new Form2(this))
{
form2.StartPosition = FormStartPosition.CenterParent;
form2.ShowDialog();
}
}
internal void example()
{
treeView1.SelectedNode = treeView1.Nodes[1];
}
private void Form1_Load(object sender, EventArgs e)
{
TreeNode node = new TreeNode("aaaa");
treeView1.Nodes.Add(node);
node = new TreeNode("bbbb");
treeView1.Nodes.Add(node);
node = new TreeNode("cccc");
treeView1.Nodes.Add(node);
}
}
}
Form2.cs
namespace ex
{
public partial class Form2 : Form
{
Form1 form1;
public Form2(Form1 form1)
{
InitializeComponent();
this.form1 = form1;
}
private void button1_Click(object sender, EventArgs e)
{
this.Close();
form1.example();
//not working
form1.treeView1.Focus();
form1.treeView1.Select();
}
}
}
Form2 really shouldn't get so intimate with Form1. Try turning your code around like this:
private void button1_Click(object sender, EventArgs e)
{
using (Form2 form2 = new Form2(this))
{
if (form2.ShowDialog(this) == DialogResult.OK) {
treeView1.Select();
example();
}
}
}
If Form2 is supposed to supply any information to add to your TreeView control, you would set up a property on Form2 and access it from within this same code block.
I'm trying to make this simple program using Visual Studio C# 2013.
program screenshot: http://i.imgur.com/4QVbaa2.png
The listbox named receiptbox modifier was set to public using the properties panel.
Basically I am using 2 forms, what I want to happen is to show the quantity + the name of the food in the form 1's listbox.
This is the code when you click the food icon on form1:
private void pictureBox1_Click(object sender, EventArgs e)
{
FoodQty form2 = new FoodQty();
form2.Show();
}
It will show form2.
This is the source-code in the form2 and when you click its Ok button:
public partial class FoodQty : Form
{
Form1 mainfrm = new Form1();
Record recordInstance = new Record();
public FoodQty()
{
InitializeComponent();
}
private void btnOk_Click(object sender, EventArgs e)
{
mainfrm.receiptBox.Items.Add((int)numericUpDown1.Value + recordInstance.foodMenuArray[1]); // converts numupdown to int and appends the string array
}
}
Try this :
in form 1 :
private void pictureBox1_Click(object sender, EventArgs e)
{
FoodQty form2 = new FoodQty(this);
form2.Show();
}
in fom2 :
public partial class FoodQty : Form
{
Form1 mainfrm = new Form1();
Record recordInstance = new Record();
public FoodQty( Form1 fr)
{
InitializeComponent();
mainfrm =fr;
}
private void btnOk_Click(object sender, EventArgs e)
{
mainfrm.receiptBox.Items.Add((int)numericUpDown1.Value + recordInstance.foodMenuArray[1]); // converts numupdown to int and appends the string array
}
}
I have set up my program so that the user can enter a new line into the combo box via a text box on a separate form (Popup form). So far the program allows the new entry and closes the popup form when the user presses the "Accept" button however the entry does not appear in the combobox and the entry is not saved.
Currently the only way to view the new entry is by the .ShowDialog(); function which opens a second instance of the first form.
Form 2
namespace RRAS
{
public partial class NewRFRPopup : Form
{
public NewRFRPopup()
{
InitializeComponent();
}
private void btnCancel_Click(object sender, EventArgs e)
{
this.Close();
}
private void btnAccept_Click(object sender, EventArgs e)
{
formRRAS main = new formRRAS();
string newRFR = txtNewRFR.Text;
main.AddRFR(newRFR);
this.Close();
main.ShowDialog();
}
private void NewRFRPopup_Load(object sender, EventArgs e)
{
}
}
}
AddRFR in Form 1
public void AddRFR(object item)
{
cmbRFR.Items.Add(item);
}
you are creating a new instance of your form1 in the accept handler:
formRRAS main = new formRRAS();
(which is why when you call showdialog you get another formRRAS appearing).
You need to pass the original formRRAS to the popup and call AddRFR on the instance passed through. I'd pass it on the constructor of the popup - i.e.
public partial class NewRFRPopup : Form
{
formRRAS _main;
public NewRFRPopup(formRRAS main)
{
InitializeComponent();
_main = main;
}
and then in your Accept handler:
string newRFR = txtNewRFR.Text;
_main.AddRFR(newRFR);
this.Close();
and of course to show the popup from formRRAS
NewRFRPopup popup = new NewRFRPopup (this);
popup.ShowDialog();
in my application i have four forms form1 form2 form3 form4 .and each form have two buttons i.e next and previous buttons to switch between forms .and my question is how can i Switch between forms without creating new instance of forms? below is my code
In Form1:
public Form1()
{
InitializeComponents();
}
private void Next_Click(object sender, EventArgs e)
{
this.Hide()
Form2 form2 = new Form2();
form2.Show();
}
In Form2:
public Form2()
{
InitializeComponents();
}
private void Previous_Click(object sender, EventArgs e)
{
this.Hide();
Form1 form1 = new Form1();
form1.Show();
}
private void Next_Click(object sender, EventArgs e)
{
this.Hide();
Form3 form3 = new Form3();
form3.Show();
}
In Form3:
public Form3()
{
InitializeComponents();
}
private void Previous_Click(object sender, EventArgs e)
{
this.Hide();
Form2 form2 = new Form2();
form2.Show();
}
private void Next_Click(object sender, EventArgs e)
{
this.Hide();
Form4 form4 = new Form4();
form4.Show();
}
In Form4:
public Form4()
{
InitializeComponents();
}
private void Previous_Click(object sender, EventArgs e)
{
this.Hide();
Form3 form3 = new Form3();
form3.Show();
}
In Main:
static void Main()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new Form1());
}
In above code i am creating new instances of forms every time..,How can i Avoid this and How can i Switch between forms without creating new instances of forms.... please help me
Since you are accessing your forms sequentially just make sure that you use the Show Method that assigns the owner to the created Form and assign it to a class level variable after you create it. Something like this should work for you.
Form1
public partial class Form1 : Form
{
Form2 frm2;
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
if (frm2 == null)
{
frm2 = new Form2(); //Create form if not created
frm2.FormClosed += frm2_FormClosed; //Add eventhandler to cleanup after form closes
}
frm2.Show(this); //Show Form assigning this form as the forms owner
Hide();
}
void frm2_FormClosed(object sender, FormClosedEventArgs e)
{
frm2 = null; //If form is closed make sure reference is set to null
Show();
}
}
Form2
public partial class Form2 : Form
{
Form3 frm3;
public Form2()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
Owner.Show(); //Show the previous form
Hide();
}
private void button2_Click(object sender, EventArgs e)
{
if (frm3 == null)
{
frm3 = new Form3();
frm3.FormClosed += frm3_FormClosed;
}
frm3.Show(this);
Hide();
}
void frm3_FormClosed(object sender, FormClosedEventArgs e)
{
frm3 = null;
Show();
}
}
Form3
public partial class Form3 : Form
{
public Form3()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
Owner.Show();
Hide();
}
}
May be a easy solution. You can make a class that contains static object of all forms that you need. So you will be able to access all these forms from any forms of your choice and the good thing is they are initialized once.
public class formList
{
private static Form1 _form1 = new Form1();
public static Form1 form1 { get {return _form1;}
.................
............
}
Try This:
Form1 myForm =(Form1) Application.OpenForms["Form1"];
myForm.Show();
You can check if the form of interest exists, and if not create it:
public static T OpenOrCreateForm<T>()
where T: Form, new() {
T result;
// Test if form exists
foreach(Form form in Application.OpenForms) {
result = form as T;
if (!Object.ReferenceEquals(null, result)) {
// Form found; and this is the right place
// to restore form size,
// bring form to front etc.
if (result.WindowState == FormWindowState.Minimized)
result.WindowState = FormWindowState.Normal;
result.BringToFront();
return result;
}
}
// Form doesn't exist, let's create it
result = new T();
// Probably, you want to show the created form
result.Show();
resturn result;
}
...
private void Previous_Click(object sender, EventArgs e)
{
Hide();
OpenOrCreateForm<Form1>();
}
private void Next_Click(object sender, EventArgs e)
{
Hide();
OpenOrCreateForm<Form3>();
}
public bool IsFormAlreadyOpen(Type FormType)
{
foreach (Form OpenForm in Application.OpenForms)
{
if (OpenForm.GetType() == FormType)
return true;
}
return false;
}
This function can be used to find out whether a form is already opened or not
call IsFormAlreadyOpen(Form4) if it returns true which means Form4 is already opened
and in your case
in every forms constructor() create next and previous forms object
and in the button click calls IsFormAlreadyOpen() to find out whether the form is already opened or not and if it already opened just bring that form in front
other wise display the form using obj.show() method
and hide or close the parent form
Looks like you are trying to achieve wizard like feature. I would recommend having a single form. Then, add a customized tab control to it. Add buttons to form that moves previous and next.
To customize tab control, this is what you need to do:
public class CustomWizard : TabControl
{
/// <summary>
/// This method traps windows message and hides other tabs in the tab control.
/// Message trapped: TCM_ADJUSTRECT
/// </summary>
/// <param name="m">Reference to Windows message</param>
protected override void WndProc(ref Message m)
{
// Second condition is to keep tab pages visible in design mode
if (m.Msg == 0x1328 && !DesignMode)
{
m.Result = (IntPtr)1;
}
else
{
base.WndProc(ref m);
}
}
/// <summary>
/// This method traps the press to stop users from selecting tab page via keyboard
/// </summary>
/// <param name="ke">Event details</param>
protected override void OnKeyDown(KeyEventArgs ke)
{
if (ke.Control && ke.KeyCode == Keys.Tab)
return;
base.OnKeyDown(ke);
}
private void InitializeComponent()
{
this.SuspendLayout();
this.ResumeLayout(false);
}
}
This tab control will only display one tab at a time. Although, at design time you can see them all. Add this and buttons to your form. On button click, merely set the SelectedIndex property of this tab control.
I had the same issue. An application I needed that had many forms and I needed to switch between forms forward n backward without losing the data. I came up with the following solution and it worked for me.
In the main (Program.cs) file, write the following two classes:
static class Variables
{
public static DataSet Configurations = new DataSet();
public static float ExchangeRate = 0;
public static Dictionary<string, int> ItemsCategories = new Dictionary<string, int>();
public static Dictionary<string, float> WeightUnits = new Dictionary<string, float>();
}
static class Forms
{
public static Form2 F_Form2 = new Form2();
public static Form3 F_Form3 = new Form3();
}
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());
}
}
The first class is used for Global variables that can be used across the forms. You can access any variable by:
Variables.ExchangeRate = 7.2; //(for ex).
The second class is where you define new instance of all your forms. You can hide n show them anywhere across all the forms by:
Forms.F_Form3.Show();
or
Forms.F_Form2.Hide();
This works smoothly and perfect for me. Try it.
Just remove the this.hide() in the first form and the [formNameHere].show(); in the second form.
Like this:
Form 1:
public Form1()
{
InitializeComponents();
}
private void Next_Click(object sender, EventArgs e)
{
this.Hide()
Form2 form2 = new Form2();
form2.Show();
}
Form 2:
public Form2()
{
InitializeComponents();
}
private void Previous_Click(object sender, EventArgs e)
{
Form1 form1 = new Form1();
this.Hide();
}
private void Next_Click(object sender, EventArgs e)
{
Form3 form3 = new Form3();
this.Hide();
}
etc.. not good at explaining, and with C# really. But this should work.
//In Form1
private static Form1 i_Instance = null;
public static Form1 Instance
{
get
{
if (Form1.i_Instance == null) Form1.i_Instance = new Form1();
return Form1.i_Instance;
}
}
// And instantiation in other forms shall look like following
Form1 F1 = Form1.Instance;
F1.Show();
Basically; Form1 has 2 buttons, Form2 has 1 button.
When you click Form2's button it checks which button on Form1 you clicked, opening Form3 or Form4 depending on which button you clicked (on Form1).
So I've utilized Mark Halls first method of passing variables between forms. Now for the second half of my closed refinement.
Form1
private void btnLogin_Click(object sender, EventArgs e)
{
// Call function while storing variable info.
Account("login");
}
private void btnRegister_Click(object sender, EventArgs e)
{
// Call function while storing variable info.
Account("register");
}
// Function used to pass Variable info to Account form while opening it as instance.
private void Account(string formtype)
{
// Generate/Name new instant of form.
frontend_account frmAcc = new frontend_account();
// Pass variable to instance.
frmAcc.CheckButtonClick = formtype;
// Show form instance.
frmAcc.Show(this);
// Hide this instance.
this.Hide();
}
Form2
// String Variable to store value from Login.
public string CheckButtonClick { get; set; }
private void btnContinue_Click(object sender, EventArgs e)
{
// If statement to open either Main form or Registration form, based on Login variable.
if (CheckButtonClick == "login")
{
// Generate/Name new instant of form.
frontend_main frmMain = new frontend_main();
// Show form instant.
frmMain.Show();
// Close this instant.
this.Close();
}
else if (CheckButtonClick == "register")
{
// Generate/Name new instant of form.
frontend_register frmReg = new frontend_register();
// Show form instant.
frmReg.Show();
// Close this instant.
this.Close();
}
}
On Form2 there are TWO radio buttons, can I adept that code to set the focus of a tab control when a form is opened? ie. if radClient is checked set focus on tabcontrol after opening winform, else if radStudent is checked set focus on tabcontrol (other page) after opening winform... and i guess don't open a winform if no radio is checked.
I believe this will set the focus;
// Sets focus to first tab.
tabRegister.SelectedTab = tabRegister.TabPages[0];
// Sets focus to second tab.
tabRegister.SelectedTab = tabRegister.TabPages[1];
In your example the first problem I see is you are closing your parent form which closes your Form1 and disposes of Your Form2, What I would do is Hide Form1 instead of Closing it, I would then create a public property on Form2 to pass in the Button that was selected. But anytime you are opening and closing multiple Forms it can get messy, what I would do would be to create UserControls for your additional Forms and swap them out in a Panel. The first example is how to do it the way that you asked.
Form
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void btnLogin_Click(object sender, EventArgs e)
{
ShowForm2("login");
}
private void btnRegister_Click(object sender, EventArgs e)
{
ShowForm2("register");
}
private void ShowForm2(string formtype)
{
Form2 f2 = new Form2(); // Instantiate a Form2 object.
f2.CheckButtonClick = formtype;
f2.Show(this); // Show Form2 and
this.Hide(); // closes the Form1 instance.
}
}
Form2
ublic partial class Form2 : Form
{
public Form2()
{
InitializeComponent();
}
public string CheckButtonClick { get; set; }
private void button1_Click(object sender, EventArgs e)
{
if (CheckButtonClick == "login")
{
Form3 f3 = new Form3(); // Instantiate a Form3 object.
f3.Show(); // Show Form3 and
this.Close(); // closes the Form2 instance.
}
else if (CheckButtonClick == "register")
{
Form4 f4 = new Form4(); // Instantiate a Form4 object.
f4.Show(); // Show Form4 and
this.Close(); // closes the Form2 instance.
}
}
}
Form3 and Form4 note since Form1 is long forgotten to these forms I search for it to Open back up
public partial class Form3 : Form
{
public Form3()
{
InitializeComponent();
}
private void Form3_FormClosed(object sender, FormClosedEventArgs e)
{
FormCollection frms = Application.OpenForms;
foreach (Form f in frms)
{
if (f.Name == "Form1")
{
f.Show();
break;
}
}
}
}
The second Option with UserControls has one Form with a Panel on it. It uses events to signal the Form to Change Controls plus a public property on UserControl2
public partial class Form1 : Form
{
string logonType;
public Form1()
{
InitializeComponent();
}
private void userControl1_LoginOrRegisterEvent(object sender, LoginOrRegisterArgs e)
{
logonType = e.Value;
userControl2.BringToFront();
}
private void userControl2_ControlFinshedEvent(object sender, EventArgs e)
{
if (logonType == "logon")
userControl3.BringToFront();
else if (logonType == "register")
userControl4.BringToFront();
}
private void userControl3_ControlFinshedEvent(object sender, EventArgs e)
{
userControl1.BringToFront();
}
private void userControl4_ControlFinshedEvent(object sender, EventArgs e)
{
userControl1.BringToFront();
}
}
UserControl1
public partial class UserControl1 : UserControl
{
public delegate void LoginOrRegisterHandler(object sender, LoginOrRegisterArgs e);
public event LoginOrRegisterHandler LoginOrRegisterEvent;
public UserControl1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
LoginOrRegisterArgs ea = new LoginOrRegisterArgs("logon");
LoginOrRegisterEvent(sender, ea);
}
private void button2_Click(object sender, EventArgs e)
{
LoginOrRegisterArgs ea = new LoginOrRegisterArgs("register");
LoginOrRegisterEvent(sender, ea);
}
}
public class LoginOrRegisterArgs
{
public LoginOrRegisterArgs(string s) {Value = s;}
public string Value {get; private set;}
}
UserControl2
public partial class UserControl2 : UserControl
{
public delegate void ControlFinishedHandler(object sender, EventArgs e);
public event ControlFinishedHandler ControlFinshedEvent;
public UserControl2()
{
InitializeComponent();
}
public string SetLogonType { get; set; }
private void button1_Click(object sender, EventArgs e)
{
ControlFinshedEvent(sender, new EventArgs());
}
}
UserControl3 & UserControl4 exactly the same except for different Class Name
public partial class UserControl3 : UserControl
{
public delegate void ControlFinishedHandler(object sender, EventArgs e);
public event ControlFinishedHandler ControlFinshedEvent;
public UserControl3()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
ControlFinshedEvent(sender, new EventArgs());
}
}
As I suggested in my comment, one of the best way I know to pass data between forms is to use events.
Basically, in the "child" forms, you declare an event that will be handled, or listened to, by the "main" form.
See the referenced answer from my comment, and if you have specific questions on how to adapt it, ask away.
Cheers