On my main form in my Windows C# application I have this method:
public void uploadNew(String newName, String filePath)
{
//Make sure file doesn't exist, then continue
if (!File.Exists(basePath + POnumber + newName))
{
File.Copy(filePath, basePath + POnumber + newName);
LogSubmit("Added New File " + newName);
listFiles();
}
else
{
//The file already exists
}
}
The meaning of the code really doesn't matter. Here's what I am trying to do. I needed a new form for a file upload form with some options and such. What I need is to send two variables back to the main form to plug into that method.
The operation is essentially this.
Main form -> Click button -> Form 2 -> operations -> Send back variables to uploadNew -> Close Form 2
I think what you want is a dialog. Essentially, you can do something like this in the MainForm:
using(var form = new Form2())
{
if(form.ShowDialog() == DialogResult.Ok)
{
// Newname and Filepapth are properties you set in the Form2
uploadNew(form.NewName, form.Filepath);
}
}
In the Form2, you probably will have a Ok, Cancel Button. For the Ok Button event, you can set this.DialogResult = DialogResult.Ok. On Cancel event, you can set it to something else.
This is from the top of my head, so some things might be off, but the concept is the same.
Also, a good idea is to move UploadFile to a new class, so you do not tie your business logic into your UI logic.
A more complete example here: How to return a value from a Form in C#?
Related
I have a button on a completion form, which when pressed opens up a windows explorer.
This was ok, when i only had 1 directory.
I now have 2 directories, which are now set from my main form.
What i would like to do, is when the button is pressed, if a combobox on my main form is for example "Apples" then opens up a coded directory.
If the combobox on my main for is "Pears" then open up a different directory.
I have the following code to open up the original directory - just dont know how to include the second, as i cant seem to access the combobox from the completion form:
private void button1_Click(object sender, EventArgs e)
{
{
this.Hide();
FrmMain form3 = new FrmMain();
form3.Show();
}
System.Diagnostics.Process.Start(new System.Diagnostics.ProcessStartInfo()
{
FileName = "C:\\Directory 1\\",
UseShellExecute = true,
Verb = "open"
});
}
Hope you can help.
Thanks - Craig.
There are quite a few ways you could do this. I'm supposing your completion form is opened from the main form. The cleanest way would be to inject the current selection of the main form's combobox upon creation. Something in the line of:
var completionForm = new CompletionForm(directoryCombo.Text);
completionForm.ShowDialog(this);
Do note that ShowDialog is relevant. This ensures that no one will change the selected directory while the completion form is active. If this not the case, and the completion form isn't modal, then a better alternative is to implement a public property in your main form:
public string SelectedDirectory => directoryCombo.Text;
And then simply access it form your completion form:
var selectedDirectory = (Owner as mainForm).SelectedDirectory;
Let's say your mainform class is called MainForm and that the combobox instance inside it is called directoryComboBox.
Now, the first step consists in creating a property in your MainForm that exposes the currently selected value of the directoryComboBox instance:
public String CurrentDirectory
{
get { return directoryComboBox.Text; }
}
In your CompletionForm class, add the following field (used as a reference to the parent MainForm instance):
private MainForm m_Parent;
and modify the constructor as follows:
public CompletionForm(MainForm parent)
{
m_Parent = parent;
}
Finally, modify the code of your MainForm in which you create a new completion form and show it to the user as follows:
CompletionForm cf = new CompletionForm(this); // this is the current instance of `MainForm` showing the completion form
cf.ShowDialog(this);
In your CompletionForm you can now have access to the currently selected value of your directoryComboBox:
System.Diagnostics.Process.Start(new System.Diagnostics.ProcessStartInfo()
{
FileName = Path.Combine(#"C:\", m_Parent.CurrentDirectory),
UseShellExecute = true,
Verb = "open"
});
You could also construct your CompletionForm instance by directly passing it the current directoryComboBox value. The approach is very similar and it doesn't require you to modify your MainForm class adding a new property. All you have to do is to edit the right CompletionForm portions of code:
private String m_CurrentDirectory;
public CompletionForm(String currentDirectory)
{
m_CurrentDirectory = currentDirectory;
}
System.Diagnostics.Process.Start(new System.Diagnostics.ProcessStartInfo()
{
FileName = Path.Combine(#"C:\", m_CurrentDirectory),
UseShellExecute = true,
Verb = "open"
});
and the MainForm method that instantiates it:
CompletionForm cf = new CompletionForm(directoryComboBox.Text);
cf.ShowDialog(this);
Prelude
At first, sorry for my bad english. :)
I read a tone of similar questions on SO, but none of them provide a solution for my problem, or I'm just stupid. :)
Question
How would I open a new chat form to talk with User1 and retain the possibility to open chat forms with other users from "users list", but block opening a chat form with a user which is already open?
I tried to find something for this, but whatever I tried, it always is same (I can open same form again and again).
So, for example, I can open a chat form with User1, I can talk with him, and I can also open a new chat form with User2 and I can talk with him. But I can also open multiple forms with User1, and with User2 to, etc.
Also, I need to pass some data from MainForm form to TalkForm, so as prototype I created this code and I tried to list, but I'm not sure how to check if a form does exist in the list:
List<TalkForm> b = new List<TalkForm>();
private void TextBoxConnectedClients_MouseDoubleClick(object sender, MouseEventArgs e)
{
if (TextBoxConnectedClients.SelectedIndex == -1)
{
return;
}
int index = this.TextBoxConnectedClients.IndexFromPoint(e.Location);
if (index != System.Windows.Forms.ListBox.NoMatches)
{
string username = TextBoxConnectedClients.SelectedItem.ToString();
TalkForm a = new TalkForm(im, username, displayname);
b.Add(a);
a.Show();
}
}
Can someone please give me some examples or tell me what I'm doing wrong? Thank you.
List<TalkForm> b = new List<TalkForm>();
You are using this list to track the forms opened for each unique user. I would update your code to check if form object is already added. You need to add using System.Linq
if (index != System.Windows.Forms.ListBox.NoMatches)
{
string username = TextBoxConnectedClients.SelectedItem.ToString();
// Check if form is already opened. Username will be unique.
var form = b.firstOrDefault(f => f.Username == username);
if (form == null) // Show new form
{
TalkForm a = new TalkForm(im, username, displayname);
b.Add(a);
a.Show();
}
else // Activate already opened form
{
form.BringToFront();
}
}
You need to expose TalkForm.Username property, if it's not in place already. And initialize that property in the constructor with username parameter.
Note: Make sure you Remove the form instance from list b when close a form for specific user.
Edit: Updated code to show already opened form as per #Draken's suggestion.
I have a problem with my dialogForm. This is the code that opens my dialogForm (this is a login form) when my mainForm starts to run.
private void indexForm_Load(object sender, EventArgs e)
{
startForm loginForm = new startForm();
loginForm.ShowDialog();
indexUsername.Text = klasseGebruikersnaam.gebruikersnaam;
}
So when my indexForm (Main form) starts , it first loads a dialogForm, which is my login form.
Now my problem is that whenever I try to acces the mainForm from another form using this code (for example when I click a button):
this.Hide();
indexForm inf = new indexForm();
inf.Show();
The dialogForm pops up again. So I want to show my mainForm but , when I load my mainForm my dialogForm always pops up.
Any way around this?
Thanks in advance.
The problem is that you are loading your loginForm from your Main Form's Load event. Which is always going to fire after the constructor of the Main Form is called. Typically you will want to launch the loginForm from somewhere before the Main Form is loaded. You could do this in your Program.cs file and make it the main entry point of the program. Or just simply check if the user is already logged in.
Here is an example of both:
Program.cs
static void Main()
{
//Auto-generated code that VS writes for you
using (var loginForm = new LoginForm())
{
if (loginForm.ShowDialog() == DialogResult.Yes) //Presumably it would only return Yes if the login was successful.
{
Application.Run(new MainForm()); //Or however you call your main form
}
}
}
Of you can just put a property on the Main Form that determines if the user is logged in. Then you can call it in the Load event still.
Load Event
if(!this.UserLoggedIn)
{
loginForm.ShowDialog();
//Do something with the dialog result.
}
In my opinion it is better to user the Program.cs approach because if the user fails to login correctly, you can just exit or handle it as needed without loading your Main Form at all. The way you currently have it, the main form must load before the login form is shown, which could be problematic.
Well, you should remove that code from your main form and call it before showing the main form.
Or you could simply set a global variable that keeps the info for the current logged in user and, if that variable is not null, don't call again the login form
So, supppose that you login form prepare an instance variable of type LoggedinUser
public class LoggedinUser
{
public string NickName {get;set;}
public string UserRole {get; set;}
...
}
then in an utility class (or in your index form) you could have a static variable
public static LoggedinUser currentOperator = null;
in your in index_form you could write
if(GlobaClass.currentOperator == null)
{
using(startForm loginForm = new startForm())
{
if(loginForm.ShowDialog() == DialogResult.OK)
GlobalClass.currentOperator = loginForm.LoggedUser;
}
}
looks like you need to add a check to see if the user is logged in around the
loginForm.ShowDialog();
something like
if(!UserLoggedIn())
{
loginForm.ShowDialog();
}
I have write the ActiveX using C# to communicate with the other browser-based system b, it need pops up an dialog in an other thread because of the existing architecture. the current behavior is that the dialog can be hidden behind if i click the browser title. Is it possible to keep the pops-up dialog always on the top of browser(IE8)? Thanks in advance.
public int operation()
{
....
MyMsgBox myMsgBox = new MyMsgBox(message,title);
evt = System.Threading.AutoResetEvent(false);
Thread showDialogThread = new Thread(ShowMsgDialog);
ShowDislogThread.SetApartmentState(System.Threading.ApartmentState.STA);
showDialogThread.Start(myMsgBox);
System.Threading.WaitHanle.WaitAll(new System.Threading.WaitHandle[] {evt});
....
}
public void ShowMsgDialog(object requestObj)
{
MyMsgBox msgBox = (MyMsgbox)requestObj;
msgBox.showDialog();
evt.Set();
}
Class MyMsgBox:Form
{
public MyMsgBox(string message, string title)
{
//do initialization....
}
}
I have tried to set the TopMost of Form to 'true', then it will be always on the top of all applications. it's not meet the requirement as the pops-up dialog need be only always on the top of browser. Thanks.
I don't think that what you want will be possible.
However, you can make a div stretched across all page and set and event on mouse move to call BringToFront on your ActiveX object. That should do the trick.
I'm working on a term paper that performs operations with complex numbers. Application looks like this:
If you click on "Calculate", will calculate the operands and the result is displayed in a new dialog box. So I have two dialogs - a main window (up on pic) to display the read result (down on pic). Unfortunately I was not able to save result in the main dialog box, which is then written to a text file. There is important piece of code:
Thank you for ideas.
In your MainForm class declare a property as
public class MainForm:Form
{
public string CalculationResult { get; set; }
...
...
//Your code here
...
...
}
then on method of calculate change it to
if(resultBool!=null)
{
CalculationResult = resultBool.ToString());
formResult dlg=new formResult(CalculationResult);
dlg.Owner=this
dlg.StartPosition=FormStartPosition.CenterParent;
dlg.ShowDialog();
}
else
{
...
...
//your code
...
...
}
and change the following line
sw.WriteLine("Result: ");
to
sw.WriteLine("Result: " + CalculationResult);
in saveData method which is in MainForm class. Hope this will work for you. Happy coding
You have to use a reference on the target form to write on it.
You have to assure that you use the correct targetForm reference. You could either create a new targetForm or use an existing one. You could for example use the "parent" form of your dialog box and set the text of the main form textbox, from a dialog box event (using this as MSDN reference):
Dim targetForm As Form = Me.parentForm
targetForm.targetTextBox.Text = "text"
Hope I helped!
In formResult create a variable which keep a reference of Main form
private MyMainForm _mainForm;
Then create one more constructor which take reference of your Main form as parameter:
public formResult(MyMainForm mainform)
{
this.InitializeComponent();
this._mainForm = mainform;
//Now you have access to public property ResultOut
this.textBoxResult.Text = this._mainForm.ResultOut;
}
After this you can use all public properties and method of your main form in second form(formResult)