Change Textbox object to Static - c#

I have little experience in C#, mostly playing with it as a hobby, and I was wondering what I needed to do to change a textbox from non-static to static.
In Visual Studio 2012, I'm trying to add a line of text using the method textbox1.AppendText("Text");, and it won't work because the textbox isn't static, while the method trying to write the code is static. I can't find the line of code where the textbox is initialized in my code, nor have I found an option in the properties that allows me to change that.
Is there a work-around, or do I need to make it static? And if I need to make it static, how would I do that? I'm at a loss.
Thank you for your help!
EDIT: adding code sample. The method below is called from a second form, same from which the value of x is determined.
public static void getMethod(int x)
{
if (x > 4)
{
textbox1.AppendText("Text");
}
else
{
textbox1.AppendText("Other text");
otherVariable = x;
}
}

It's not clear from your post which GUI framework you're using. Both Winforms and WPF have a TextBox class.
But, to the point of your question: you could in the object where the TextBox is declared and created, also have a static field to which you assign that reference. But that would be a poor design choice, IMHO.
It's not clear what your static code is doing, where it's declared, or who called it (another failing of your question is that you did not provide any code, never mind a concise, complete code example), but assuming the static method is not in the UI object that owns the TextBox instance itself (if it is, then you just need to make the method non-static), the the correct way to address this would be for the UI object that does know about the TextBox instance to have some public method or property used to set the text, and then for the code that invokes your static method to pass the reference of that UI object to the static method, so that it can use the member you added.
For example:
class Form1 : Form
{
public string FieldText
{
get { return textBox1.Text; }
set { textBox1.Text = value; }
}
}
and elsewhere:
static void SomeMethod(Form1 form)
{
// ...do some stuff...
form.FieldText = "some text";
// ...do some other stuff...
}
In your specific scenario, you seem to have two forms: one containing the textbox1 member, and another that passes an int value to a method, where you want to be able to add some text to the TextBox1 based on the value.
In that case, it would look more like this:
class Form1 : Form
{
public void AppendFieldText(string text)
{
textbox1.AppendText(text);
}
}
and in the static method:
public static void getMethod(int x, Form1 form)
{
if (x > 4)
{
form.AppendFieldText("Text");
}
else
{
form.AppendFieldText("Other text");
otherVariable = x;
}
}
Naturally, the caller of the getMethod() method will need the reference for the form parameter; you will have to pass that somehow to that second form which is calling this method, so that it can pass it to the method.
Note that in both of my examples, I have not exposed the TextBox object itself. You should follow this example, exposing only the minimum amount of functionality needed in order to get the job done. This helps ensure that the TextBox object doesn't wind up getting used in appropriately by some other code, and especially helps ensure that your classes remain reasonably decoupled.
On that latter point, I will mention that your code example is still pretty bare. There are other techniques which can solve this problem with even less coupling between the types. But again, lacking a good code example, it's not possible to know for sure what would work, never mind what would be best.
The above example is appropriate, given the information you've shared.
If you would like to edit your question to provide better, more specific detail, a better, more specific answer could be provided.

you can do something like below
private void button3_Click(object sender, EventArgs e)
{
getMethod(textBox1,5);
}
public static void getMethod(TextBox textbox1,int x)
{
if (x > 4)
{
textbox1.AppendText("Text");
}
else
{
textbox1.AppendText("Other text");
otherVariable = x;
}
}

Textboxes aren't static. And you can't make them static, they are all instanciated. The name of your textbox is the instance name.
So just use the text property on the instance of the text box.
textbox1.Text = "Text";
If you want to Append one just do:
textbox1.Text = String.Concat(Textbox1.Text, "more text");
same thing about could also be seen as:
textbox1.Text = textbox1.Text + "more text";

Related

how to know which form called another form in C#

I am having multiple forms with Buy button provided. The forms i am having are LawnA.cs and Lawnb.cs, i want to use single Buy.cs form for both of these forms. I mean I want to know what form called the Buy.cs.
In Form LawnA.cs
buy.lotAtobuy = this;
buy.ShowDialog();
In Form LawnB.cs
buy.lotBtobuy = this;
buy.ShowDialog();
In Form Buy.cs
public LawnA lotAtobuy;
public LawnB lotBtobuy;
((LawnA)lotAtobuy).textBox1.Text;
((LawnB)lotBtobuy).textBox1.Text;
In class Buy.cs, I want to execute:
((LawnA)lotAtobuy).textBox1.Text;
if LawnA.cs called Buy.cs while if LawnB.cs called Buy.cs I want to execute this code:
((LawnB)lotBtobuy).textBox1.Text;
You need to to define separate object for each class instead for that define the variable as object, and check the type of object before assigning the text. Which means the declaration of that variable in Buy.cs will be:
public object lotToBuyInstance;
So that you can get the type of object and compare before use, that would be like thi:
if (lotToBuyInstance.GetType() == typeof(LawnA))
{
((LawnA)lotAtobuy).textBox1.Text;
}
else if (lotToBuyInstance.GetType() == typeof(LawnB))
{
((LawnB)lotAtobuy).textBox1.Text;
}
// and so on
Consider that you wanted to create another class(let it be some LawnC) then you need not to create an object of that type and make changes as per that, Just add another condition in your if else if ladder to make them work
Try this in the constructor for the receiving form:
using System.Diagnostics;
public FormThatWasCalled
{
string caller = new StackTrace().GetFrame(1).GetMethod().DeclaringType.Name;
InitializeComponent();
}

C# - Update GUI datagridview from another thread using delegate

I'm trying to update a datagridview with some data calculated in a different class and thread, using a delegate. Unfortunately I'm having trouble with a variety of different errors, depending on the approach I try.
The code I am trying to execute in the form thread looks like this:
public partial class AcquireForm : Form
//
// ...
//
// update the grid with results
public delegate void delUpdateResultsGrid(int Index, Dictionary<string, double> scoreCard);
public void UpdateResultsGrid(int Index, Dictionary<string, double> scoreCard)
{
if (!this.InvokeRequired)
{
//
// Some code to sort the data from scoreCard goes here
//
DataGridViewRow myRow = dataGridViewResults.Rows[Index];
DataGridViewCell myCell = myRow.Cells[1];
myCell.Value = 1; // placeholder - the updated value goes here
}
}
else
{
this.BeginInvoke(new delUpdateResultsGrid(UpdateResultsGrid), new object[] { Index, scoreCard});
}
}
Now, I need to get this method to run from my other thread and class. I have tried:
public class myOtherClass
//
// ...
//
private void myOtherClassMethod(int myIndex)
{
// ...
AcquireForm.delUpdateResultsGrid updatedelegate = new AcquireForm.delUpdateResultsGrid(AcquireForm.UpdateResultsGrid);
updatedelegate(myIndex, myScoreCard);
}
Unfortunately this gives an "Object reference is required for the non-static field, method, or property AcquireForm.UpdateResultsGrid(int, System.Collections.Generic.Dictionary)" error. I seem to be unable to reference the UpdateResultsGrid method at all...
I have noticed that
public class myOtherClass
//
// ...
//
private void myOtherClassMethod(int myIndex)
{
// ...
AcquireForm acquireForm = new AcquireForm();
acquireForm.UpdateResultsGrid(myIndex,myScoreCard);
}
does not throw any errors when compiling, but it tries to create a new form and that is something I do not want to do. I don't want to create a new instance of AcquireForm, I want to reference the pre-existing one, if that's possible.
I have also tried making the UpdateResultsGrid method static, but this throws up problems with several things incuding the use of "this.(anything)".
I've also tried moving the majority of the UpdateResultsGrid method into myOtherClassMethod, leaving behind in the AcquireForm class just the delegate. Again, this does not work because many of the references to UI objects break (there aren't any dataGridViews in scope).
I'm starting to run out of ideas here. Unfortunately I'm rather new to C# (as you can probably tell), and I'm editing someone else's code rather than writing my own entirely from scratch. If anyone could offer some advice on this problem it'd be most appreciated.
Make sure your objects are communicating with each other: Your myOtherClass is going to have to know about the AcquireForm object - you can't just create a new one (as you've discovered). You'll need to pass the AcquireForm object into the myOtherClass object (myOtherObject.SetForm(myAcquireForm, for example) and reference it when you need to.
In case you're having issues with invoking this might be of help - how I invoke a "next" button click:
BeginInvoke(new Action(()=>button_next_Click(null,null)));
Moreover, it sounds like maybe this should not be separate classes and you should be utilising a BackgroundWorkder instead.

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!

Single reusable function to open a single instance of form

I am trying to create a reusable function that can open a single instance of form. Means if a form is not already open it should create and show the new form and if already open it should bring the existing form to front.
I was using the following function,
if (Application.OpenForms["FPSStorageDemo"] == null)
{
FPSStorageDemo fp = new FPSStorageDemo();
fp.Name = "FPSStorageDemo";
fp.Show();
}
else
{
((FPSStorageDemo)Application.OpenForms["FPSStorageDemo"]).BringToFront();
}
But I have to write this code again and again whereever I have to open a form. But I need a single reusable function that can do this job.
I wrote a function like,
void OpenSingleInstanceForm(Type TypeOfControlToOpen)
{
bool IsFormOpen = false;
foreach (Form fm in Application.OpenForms)
{
if (fm.GetType() == TypeOfControlToOpen)
{
IsFormOpen = true;
fm.BringToFront();
break;
}
}
if (!IsFormOpen)
{
Object obj = Activator.CreateInstance(TypeOfControlToOpen);
//obj.Show(); //Here is the problem
}
}
But at the end I don't know how to show the new form instance. Can anybody suggest how to do it? Is this wrong or there is another way to do this?
Thanks in advance.
public static class FormUtility
{
public static FormType GetInstance<FormType>() where FormType : Form, new()
{
FormType output = Application.OpenForms.OfType<FormType>().FirstOrDefault();
if(output == null)
{
output = new FormType();
}
//you could add the show/bring to front here if you wanted to, or have the more general method
//that just gives a form that you can do whatever you want with (or have one of each).
return output;
}
}
//elsewhere
FormUtility.GetInstance<Form1>.BringToFront();
I'd also like to take the time to mention that while having methods like this are quick and easy to use, in most cases they are not good design. It leads you to the practice of just accessing forms globally rather than ensuring that when forms need to communicate with each other they do so by exposing the appropriate information through the appropriate scope. It makes programs easier to maintain, understand, extend, increases reusability, etc. If you have trouble determining how best for two or more forms to communicate without resorting to public static references to your forms (which is exactly what Application.OpenForms is) then you should feel free to post that question here for us to help you solve.
You are looking for Singleton
Check this Implementing Singleton in C#

Good way to define a method

What is the best / good way to implement method calls.
For eg: From the below which is generally considered as best practice. If both are bad, then what is considered as best practice.
Option 1 :
private void BtnPostUpdate_Click(object sender, EventArgs e)
{
getValue();
}
private void getValue()
{
String FileName = TbxFileName.Text;
int PageNo = Convert.ToInt32(TbxPageNo.Text);
// get value from Business Layer
DataTable l_dtbl = m_BLL.getValue(FileName, PageNo);
if (l_dtbl.Rows.Count == 1)
{
TbxValue.Text = Convert.ToInt32(l_dtbl.Rows[0]["Value"]);
}
else
{
TbxValue.Text = 0;
}
}
Option 2 :
private void BtnPostUpdate_Click(object sender, EventArgs e)
{
String FileName = TbxFileName.Text;
int PageNo = Convert.ToInt32(TbxPageNo.Text);
int Value = getValue(FileName, PageNo);
TbxValue.Text = Value.ToString();
}
private int getValue(string FileName, int PageNo)
{
// get value from Business Layer
DataTable l_dtbl = m_BLL.getValue(FileName, PageNo);
if (l_dtbl.Rows.Count == 1)
{
return Convert.ToInt32(l_dtbl.Rows[0]["Value"]);
}
return 0;
}
I understand we can pass parameters directly without assigning to a local variable... My question is more about the method definition and the way it is handled.
If you're subscribing to the event automatically, I don't think it's particularly bad to have a method with the event handler signature which just delegates to a method which has the "real" signature you need (in this case, no parameters).
If you're subscribing manually, you can use a lambda expression instead:
postUpdateButton.Click += (sender, args) => PostUpdate();
and then do the work in PostUpdate. Whether you then split up the PostUpdate into two methods, one to deal with the UI interaction and one to deal with the BLL interaction is up to you. In this case I don't think it matters too much.
How you structure UI logic to make it testable is a whole different matter though. I've recently become a fan of the MVVM pattern, but I don't know how applicable that would be to your particular scenario (it's really designed around Silverlight and WPF).
A couple of other comments though:
Conventionally, parameters should be camelCased, not PascalCased
Do you genuinely believe you're getting benefit from prefixing local variables with l_? Isn't it obvious that they're local? Personally I'm not keen on most of the variable names shown here - consider naming variables after their meaning rather than their type.
Using a DataTable to return information is a somewhat error-prone way of doing things. Why can the BLL not return an int? to indicate the value (or a lack of value)?
here is what i like to to if i don't implement mvc. and i'm assuming web here.
I'd do option 2 first but instead of having the buttons code set the text id create a property to set the text boxs value.
I do this because if something else sets the textbox value then you are going to duplicate code. bad if you change a name or control type.
According to your example, option 2 is the way to go. Option 1 knows about your form and how to display data on it, which violates the SRP.

Categories

Resources