How do i show a new form from usercontrol? - c#

I'm making a usercontrol which is a file manager (cut ,copy ,paste .. etc)
so while moving/coping files .. i had to show a messagebox when the file is already exist .. to let the user to confirm overwrite it or cancel .. but i need 4 buttons [YES][YES TO ALL][NO][CANCEL]
so i made a new form called "MyMessageBox" which contains the 4 buttons and a label.
my problem is .. in (userControl1.cs) i can't initialize the form like this:
MyMessageBox msgbox = new MyMessageBox("overwrite file ?");

First of all you need to make sure that your usercontrol has visibility of the form that you created(i.e. if your form is in another namespace or project you will need to use a using statement or add a project reference in order for your usercontrol to be able to use it.) and that your constructor is what you are thinking it is as M.Babcock is suggesting. You can try something like this
UserControl:
public partial class UserControl1 : UserControl
{
MyMessageBox msgbox;
public UserControl1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
msgbox = new MyMessageBox("Overwrite File ?");
msgbox.ShowDialog();
}
}
CustomMessageBox:
public partial class MyMessageBox : Form
{
public MyMessageBox( string Message)
{
InitializeComponent();
label1.Text = Message;
}
}
Which will give you a result like this.

Related

How to access a MainWindow variable from a page in C# WPF?

I am trying to code a WPF desktop Application. Currently i have a Main Window (MainWindow) and a page (Pageone) under the same solution. From my MainWindow.xaml.cs page, i have a variable (proc1) which i want to pass to my Pageone.xaml.cs page and maybe even more pages in the future to access and use for some calculation.
However i cant seem to find a method to successfully do this, i have tried making my variable "public", and instantiate the MainWindow object for my page to access it but it doesn't seem to work. (A field initializer cannot reference the non-static field, method, or property 'Pageone.pog')
MainWindow.xaml.cs
public string proc1;
public void startTroubleshootButton_Click(object sender, RoutedEventArgs e)
{
try
{
var selectedProcess = listViewProcesses.SelectedItems[0] as myProcess;
if (selectedProcess == null)
{
MessageBox.Show("no selection made");
return;
}
proc1 = selectedProcess.processName;
MessageBox.Show($"you have selected the {proc1} application ");
Pageone pg = new Pageone(this);
this.Content = pg;
}
catch(ArgumentOutOfRangeException)
{
return;
}
}
Pageone.xaml.cs
public partial class Pageone : Page
{
public Pageone(MainWindow mainWindow)
{
InitializeComponent();
}
MainWindow pog = new MainWindow();
string procName = pog.proc1;
...
I've heard that i will maybe need to use something called the MVVM or code a parameterized constructor but i'm not sure if its related to the code i'm doing. Is there a better way to go about coding this? Thanks.
It can be done like:
var window = (MainWindow)Application.Current.MainWindow;

Save/Open Dynamically Created Controls In a Form

I am trying to develop a program in which it could create forms and add controls to it at runtime.
It also should be able to save, (Open and Edit) the forms created with the new controls added it at Runtime.The Application starts In the Main form.
CODE BEHIND MAIN Form
private void Btn_CREATE_FORM_Click(object sender, EventArgs e)
{
Form_Properties fp = new Form_Properties();
fp.Show();
}
private void BTn_ADD_BTN_Click(object sender, EventArgs e)
{
/// WHAT CODE SHOULD I ENTER TO ADD BUTON TO NEW FORM
}
Basically the main form is used to create/open/save new forms and add controls to it.
When the user clicks on Create New Form button the user will be presented with the following form (FORM_PROPERTIES) in which the user can customize the name, width and height of the new form.
CODE BEHIND FORM_PROPERTIES Form
public partial class Form_Properties : Form
{
public Form_Properties()
{
InitializeComponent();
}
String form_name;
int form_width;
int form_height;
private void Btn_OK_Click(object sender, EventArgs e)
{
form_name = TBox_NAME.Text;
form_width = Convert.ToInt32(TBox_WIDTH.Text);
form_height = Convert.ToInt32(TBox_HEIGHT.Text);
New_Form nf = new New_Form();
nf.Text = form_name;
nf.Width = form_width;
nf.Height = form_height;
nf.Show();
}
}
The following image shows what happens at runtime based on the code I have written so far.
ISSUES
Need help to Write Code
To add controls to new form created.
To Save/Open/Edit Functionalities.
I also need to know the method to access properties of added controls at runtime.
eg: If the user adds a text box to the NEW FORM and decides to type some text in it, I need a method to save that text.
Is there a way for me to name the added controls?
It seems you want to build some kind of WinForms' form designer. Your program would be similar to Glade (though Glade is much more powerful).
I'm afraid the question is too broad, though. There are many questions to answer, for example, how do you describe the created interface.
While Glade uses XML, you can choose another format, such as JSON. Let's say that you have a TextBox with the word "example" inside it.
{ type:"textbox" text:"example" }
It seems you want to add your components to the form as in a stack. Maybe you could add its position. For example, a form containing a label
("data"), a textbox ("example"), and a button ("ok"), would be:
{
{ pos:0, type:"label", text:"data" },
{ pos:1, type:"textbox", text:"example" },
{ pos:2, type:"button", text:"ok" },
}
But this is just a representation. You need to a) store this when the form is saved, and b) load it back when the form is loaded.
For that, you will need a class representing the components, such as:
public class Component {
public override string ToString()
{
return string.Format( "position:{0}, text:{1}", this.Position, this.Text );
}
public int Position { get; set; }
public string Text { get; set; }
}
public class TextBoxComponent: Component {
public override string ToString()
{
return base.ToString() + "type:\"textbox\"";
}
}
...and so on. This is a big task, I'm afraid, with no simple answer.

How to pass window and string parameter from code behind into User Control

I have a bit off header that I need global to a few files so I have made a user control (I can't use the main window as this isn't global to all files) however there's two parameters that my user control needs, ScreenName and MainWindow to navigate on the home button click. Here is what I have tried so far:
public Header(MainWindow mainWindow, string screenName)
{
InitializeComponent();
DataContext = this;
ScreenName = screenName;
MainWindow = mainWindow;
ScreenNameTextBlock.Text = ScreenName;
}
public string ScreenName { get; set; }
public MainWindow MainWindow { get; set; }
private void Hyperlink_OnClick(object sender, RoutedEventArgs e)
{
//need to navigate home here
MainWindow.LoadScreenByCode("Menu");
}
You can probably assume the corresponding XAML as it's just a hyperlink and a textblock, but if you need it let me know.
I can include the user control like so:
<controls:Header x:Name="Header"></controls:Header>
But I can't figure out how to assign the parameters. If I try in the codebehind I can access the values like this:
Header.MainWindow = Shell;
Header.ScreenName = "Name";
But this causes the values to be null. Sorry if this is an easy issue, I am new to UserControls.
To access the main window of your application you should get the running instance of it as the following:
MainWindow myRunnningMainWindow = (Application.Current.MainWindow as MainWindow);
if(myRunningWindow!=null)
{
//Do what you want with the main window
}

How can I make a form's controls not load until at least the frame of the form has been displayed?

I have a C# Winforms form that has a ton of custom controls that take about 10 seconds to load. Right now, when I click the menu item to open my form, the menu freezes for 10 seconds, and then the form just pops up ready to go. What I'd like to do is the following: As soon as you click the appropriate menu item to open up my form, I want to display the form immediately, but perhaps with just a red background and no controls on it. Then the form can start trying to load all my controls. That way the user sees that their mouse click opened the new form, and it doesn't look like the whole app froze. Moving it to a new thread is not an option.
Have you tried putting your user controls in a seperate user control, then instantiate it in your Shown event and then add it to your form.
i.e. something like this
Form1
public partial class Form1 : Form
{
UserControl1 usr;
public Form1()
{
InitializeComponent();
}
private void Form1_Shown(object sender, EventArgs e)
{
usr = new UserControl1();
usr.Dock = DockStyle.Fill;
panel1.Controls.Add(usr);
}
}
UserControl1
public partial class UserControl1 : UserControl
{
public UserControl1()
{
System.Threading.Thread.Sleep(10000);
InitializeComponent();
}
}

Update form from form closing event on another form

I am trying to update a datagridview on my 'switchboard' to solve a concurrency issue. The switchboard has many checkboxes to check off when certain processes are done. When I click a checkbox on a record that has been edited I get a concurrency error as the dgv is not up to date.
I tried doing this:
How to refresh datagridview when closing child form?
to no avail as it raises other errors throughout my project.
Any help on how to refresh my datagridview on my switchboard on the form closing of another form would be great.
Thanks
public partial class frmSwitch : Form
{
public frmSwitch()
{
//'add a label and a buttom to form
InitializeComponent();
}
public void PerformRefresh()
{
this.propertyInformationBindingSource.EndEdit();
this.propertyInformationTableAdapter.Fill(this.newCityCollectionDataSet.PropertyInformation);
this.propertyInformationDataGridView.Refresh() }
}
public partial class frmSummary : Form
{
frmSwitch _owner;
public frmSummary(frmSwitch owner)
//public frmSummary()
{
InitializeComponent();
_owner = owner;
this.FormClosing += new System.Windows.Forms.FormClosingEventHandler(this.frmSummary_FormClosing);
}
private void frmSummary_FormClosing(object sender, FormClosingEventArgs e)
{
_owner.PerformRefresh();
}
That is what I attempted to do but it caused issues in other instances when I needed to open Form2. The issue specifically occurs in the original opening of form 2 which is as follows:
private void propertyInformationDataGridView_CellContentDoubleClick(object sender, DataGridViewCellEventArgs e)
{
System.Data.DataRowView SelectedRowView;
newCityCollectionDataSet.PropertyInformationRow SelectedRow;
SelectedRowView = (System.Data.DataRowView)propertyInformationBindingSource.Current;
SelectedRow = (newCityCollectionDataSet.PropertyInformationRow)SelectedRowView.Row;
frmSummary SummaryForm = new frmSummary();
SummaryForm.LoadCaseNumberKey(SelectedRow.CaseNumberKey, true, null);
SummaryForm.Show();
}
It sounds like you are trying to create a new instance of your Switchboard form instead of modifying the existing instance of the form. When you open a form from the switchboard, I would suggest passing in instance reference to the switchboard form. Then, when you close the opened form, in your form_closing event you would refer to the passed in instance as the Switchboard form to update.
This method and others are specified in this article:
http://colinmackay.co.uk/blog/2005/04/22/passing-values-between-forms-in-net/

Categories

Resources