Error CS1674 trying to open second form - c#

I'm sure, this is a total newbie question, but I'm hanging for hours now...
My main form should have a method that opens a second form with a textbox. Just to have a kind of messagebox with scrollbar. I know there are lots of examples out there, but they are all too extensive for my needs. So here is my code so far:
private void ShowBox (string info)
{
if (info != "")
{
using (var form = new Message())
{
// work to do
}
}
}
public partial class Message : Form
{
public Message()
{
InitializeComponent();
say.Text = "OK";
}
}
Message is my 2nd form. I receive CS1674 (type used in a using statement must be implicitly convertible to 'System.IDisposable') error on the using line.
I already took this as reference Opening and closing form2 from form1 C# but I don't see the difference to my code.
What am I doing wrong?

Message probably resolves as System.Windows.Forms.Message which is a structure.
Ctrl+Click on your usage of new Message() will jump to the declaration.

In namespace System.Windows.Forms there is already a struct named Message. Seems like the compiler confounds your class with that. You should rename your form to something like MessageForm.

Related

C# Cannot implicitly convert one form to another form

So i am trying to store my main form and open a new one however i get this error, here is the code:
I have this at form level
public static frmAddBook frmkeepBooks = null;
public frmMain()
{
InitializeComponent();
frmkeepBooks = this;
}
The error underlines "this" saying it "Cannot inplicitly convert type Books.frmMain to Books.frmAddBook"
Change the first line into:
public static frmMain frmkeepBooks = null;
The types should be equal (or in herited) and probably it is not.
Are you trying to just show the new form on top of the old as a dialog keeping the old form up? I don't quite understand why you are trying to set your instance of frmMain to equal a null instance of frmAddBook.
if you are trying to open new form as a dialog you would do something like this:
public static frmAddBook frmkeepBooks;
public frmMain()
{
InitializeComponent();
frmKeepBooks = new frmAddBook();
/* if you want to display the 2nd form ontop of the first disallowing
user interaction on the first until the 2nd form closes */
frmKeepBooks.ShowDialog();
// If you want to allow interaction on either form
frmKeepBooks.Show();
/* maybe you don't want to display the first form
anymore after the 2nd form is displayed */
this.Visible = false;
}
I think this question needs some clarification on what you are trying to do exactly.

System.FormatException - Appeared after I've added a new class

(I'm new to C#). After I've split-up my class (which included they GUI and the calculation of the code) in each of its parts. (One class the GUI, one the program itself), it shows evertime I press on the Button for the calculation: System.FormatException
Following is the first class
class Annuitätenrechner : Annuitätendarlehen
{
public void AnRechner() {
int betrag;
betrag = Convert.ToInt32(betrag2.Text);
betrag = int.Parse(betrag2.Text);
[Irrelevent stuff following...]
}
}
Second class
public partial class Annuitätendarlehen : Window
{
public Annuitätendarlehen()
{
InitializeComponent();
}
private void berechnen2_Click(object sender, RoutedEventArgs e)
{
var AnRe = new Annuitätenrechner();
AnRe.AnRechner();
}
Got no idea why it doesnt work <.<
Rene's comment makes great sense already.
I would like to add my 2 cents:
1) In case you want to break whenever an exception is thrown, you could take a look at VS 2013 and before or enter link description here.
2) You can check the $exception virtual variable in watch window and check its "stack" or inner exceptions for more detail of the error. Looking into the detail of the exception and the error message always helps.
For the question itself, you could also took a look at Int32.Parse or Convert.ToInt32's document and check when "FormatException" will be thrown.
According to the document, betrag2.Text was not a valid integer when the button was triggered.

How to set text in form from another form?

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)

c# objects modification: a strange behaviour

I'm developing a WPF C# application and I have a strange behaviour in modification of objects. I try to explain it in general way.
Suppose that you have an object of a class described as follows:
public class A
{
int one;
bool two;
List<B> listofBObjects;
}
where B is:
public class B
{
int three;
int four;
}
I pass an instance of A class and an instance of B class from a window to another, only defining two variables of type A and B in the second window and passing them before the Show() method, with the following code, executed into an instance of window FirstWindow:
SecondWindow newWindow = new SecondWindow();
newWindow.instanceOfA = this.instanceOfA; //instanceOfA is of type A
newWindow.instanceOfB = this.instanceOfA.listOfBObjects[0]; //instanceOfB is of type B
newWindow.Show();
If I have to repeat this code twice(that is, opening twice the window), in the first execution everything works as expected, infact if I modify values in instanceOfB variable, I see the modification also in instanceOfA variable. But, in the second execution, the modification in instanceOfB does not affect instanceOfA...
The modifications are done in newWindow. For example:
this.instanceOfB.three++;
this.instanceOfB.four--;
Imagine that you are in the FirstWindow. Click on a button and SecondWindow opens, passing both variables as described above. In SecondWindow, do some modifications, click on OK and SecondWindow closes, returning control to FirstWindow. If I reclick on the same button, I reopen SecondWindow. If I do modifications now, they do not affect both variables.
I try to have a look (in VS2012) at both variables in the console with control expression and I see that, in the first pass of code, both variables changes when code above is executed but, in the second pass of code, only instanceOfB changes...
EDIT:
Following the code that I use to pass parameters to SecondWindow...types are explaind below
IntermediatePosition obj = ((FrameworkElement)sender).DataContext as IntermediatePosition; //IntermediatePosition is Class B
IntermediatePositionsSettingsWindow ips = new IntermediatePositionsSettingsWindow();
ips.currentIntermediatePosition = obj;//this is the instanceOfB
ips.idxOfIpToModify = obj.index;
ips.currentSingleProperty = this.currentPropertyToShow; //this is the instanceOfA object
ips.sideIndex = this.sideIndex;
ips.ShowDialog();
Consider that obj is given by a button selection into a datagrid, in which each row represents an IntermediatePosition object. In the datagrid, there is a column button and, clicking by buttons, IntermediatePositionsSettingsWindow is opened with the proper data
EDIT:
I've performed the folloqing check:
this.currentPropertyToShow.sides[this.sideIndex].intermediatePositionList[i].Ge‌​tHashCode() == obj.GetHashCode()
where i is the index of related IntermediatePosition object. At first usage of IntermediatePositionsSettingsWindow the objects result equals, but in second usage they are different
Why this thing happens?
If it is needed any other clarification, I will edit the question
Thanks
It's difficult to give a proper answer to this, as there is insufficient code to correctly work out the issue. However, if you are databinding, then I believe you need to implement this interface. It is possible that you're issue is simply that you're model is not reflecting the changes to the screen.
I can't reproduce your problem. Here's a simplified representation of your class relation (as I understood from your question). Please let us know if this is correct:
public partial class MainWindow : Window
{
internal A instanceOfA;
internal B instanceOfB;
public MainWindow()
{
InitializeComponent();
instanceOfB = new B() { };
instanceOfA = new A() { listOfBObjects = new List<B>() { instanceOfB } };
}
private void Button_Click(object sender, RoutedEventArgs e)
{
SecondWindow newWindow = new SecondWindow();
newWindow.instanceOfA = this.instanceOfA; //instanceOfA is of type A
newWindow.instanceOfB = this.instanceOfA.listOfBObjects[0]; //instanceOfB is of type B
newWindow.Show();
}
}
public partial class SecondWindow : Window
{
internal A instanceOfA;
internal B instanceOfB;
public SecondWindow()
{
InitializeComponent();
Loaded += SecondWindow_Loaded;
}
void SecondWindow_Loaded(object sender, RoutedEventArgs e)
{
MessageBox
.Show(String.Format("{0}",
this.instanceOfB == this.instanceOfA.listOfBObjects[0]));
this.instanceOfB.three++;
this.instanceOfB.four--;
}
}
Note: this is not an answer, just trying to establish some common ground for further discussions, as comments don't leave you enough freedom for code samples.
Thanks to #pm_2 and #BillZhang comments, I found a row in my code in which this.currentPropertyToShowwas edited. After the returning back at first window, infact, I perform the refresh of the window, but it is not needed to edit this.currentPropertyToShow, so I have commented it and everything works!
Thanks everybody for precious comments and suggestions!

In C# what is the best way to close a newly opened form if there is a failure in CTOR/Load event?

What is the best method [pattern] to close a newly opened Windows form in C#/.NET if there is a trappable error in the CTOR/_Load event ?
i.e.,
bool loadError;
MyForm_Load(...) {
try {
} catch (SomeException ex) {
// Alert the user
MessageBox.Show("There was a critical error. The form will close. Please try again.");
// There was some sort of error, and I just want the form to close now.
loadError = true;
return;
}
}
Now I want to act on loadError.
I've tired using the Activate event, but that yielded no results. Any suggestions on what the best way to go about doing this is ?
Update: Perhaps I should have been a little more explicit. Doing a "this.Close();" during the forms Load event will cause an exception to be thrown as a form can't be closed and the exception will be "Cannot call Close() while doing CreateHandle()".
As I mentioned in the comments, I tried with a sample example and called this.Closed() inside of the catch block. It worked just fine. The application showed the message box and didn't show me the form. I am using .NET3.5 SP1, though.
Suppose this error happens in earlier version of .NET Framework, can you try to see whether any of the followings works for you or not? They, again, seem to work fine on my machine, yet, cannot guarantee whether they will work on yours, though.
Put this.Close() in the finally block to see it works
finally {
if (this.loadError)
this.Close();
}
Defer the Form.Close() after Form.OnLoad event handler completes.
See the sample below: this does not contain any anonymous delegate or lambda expression for older versions of .NET FW. Please forgive me for partial class :)
using System;
using System.Windows.Forms;
namespace ClosingFormWithException
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
public delegate void InvokeDelegate();
private void Form1_Load(object sender, EventArgs e)
{
try
{
MyTroublesomeClass myClass = new MyTroublesomeClass();
}
catch (ApplicationException ex)
{
MessageBox.Show("There was a critical error. The form will close. Please try again.");
this.BeginInvoke(new InvokeDelegate(CloseTheForm));
}
}
private void CloseTheForm()
{
this.Close();
}
}
class MyTroublesomeClass
{
public MyTroublesomeClass()
{
throw new ApplicationException();
}
}
}
Use the combination of 1 and 2 if 2 does not work:
finally {
if (this.loadError)
this.BeginInvoke(new InvokeDelegate(CloseTheForm));
}
Have you tried calling this.Close() in the FormShown event? That event is fired once when your form is first shown. You could check your error condition there and then call close.
I think you should call form.Dispose() and then set form = null. This should cover for the main usage scenario.

Categories

Resources