c# show Settings value in debug mode at runtime - c#

Hello potential Readers
I wanted to know if one can see the stored value of a settingsobjet at runtime in debug. Like how you see the value of a variable if you hover above them. I know i could just always make :
string a = Properties.Settings.Default.(myObjectName) and hover over a, but I want to know if there is a quicker way. I already tried Google but it didn't really show me anything that answer my question:(
image of the settings
(i'm using visualstudios 2015 and .Net Framework 4.5.2).
Properties.Settings.Default.FileLocation = ProfileListBox.OpenFile;
//problem: I use the Filelocation quite often in my code but have to always backtrack to see what the currently assigned value for Filelocation is.
If you know of an other way to see the Filelocationvalue (in my case) it would be very appriciated if you could tell.

My be this approach helps you with your problem:
By simply handling the PropertyChanged Event of the Settings.
void test() {
Settings.Default.PropertyChanged += Default_PropertyChanged;
}
private void Default_PropertyChanged(object sender, PropertyChangedEventArgs e)
{
if (e.PropertyName == "MyProperty")
{
var tValue = Settings.Default.PropertyValues[e.PropertyName].PropertyValue.ToString();
toolStripStatusLabelMessage.Text = String.Format("Property {0} changed to {1} ", e.PropertyName , tValue);
}
}

Related

Cannot explicitly call operator or accessor and static

I have two stupid questions :
The first one :
I have already asked this and I'm truly sorry to ask it again (even more so because there are a lot of posts about it), but now I really don't understand why that happens even if I read every other post, here is my code :
public class PageTitre {
...
public void situation(string s) {
onglet.get_Range("C11").Value = "(" + s + ")";
}
}
public class PPE_Process {
public static PageTitre pageTitre;
public static void MainProcess() {
...
pageTitre = new PageTitre();
...
}
}
public partial class PPE_Ribbon {
private void SituationEditBox_TextChanged(object sender, RibbonControlEventArgs e)
{
PPE_Process.pageTitre.situation(SituationEditBox.Text);
}
}
I have tried some other things, like putting situation as a variable of PageTitre and having a get and a set, and
private void SituationEditBox_TextChanged(object sender, RibbonControlEventArgs e)
{
PPE_Process.pageTitre.set_situation(SituationEditBox.Text);
}
Or
private void SituationEditBox_TextChanged(object sender, RibbonControlEventArgs e)
{
PPE_Process.pageTitre.situation = SituationEditBox.Text;
}
But nothing worked, with the same error: cannot explicitly call operator or accessor.
I guess there is a problem with the static? If that is the case, here is my second question:
Second one :
I read a lot of documentation about it but I really can't understand what is the use of "static"... Is it just so that we can't change the value outside of the class, or something like this? Then, would it really change something if I take off every static there is in my code?
Again, I am sorry that you have to answer this question again and again, but I understand a lot better if that is directly related to my code, and not someone answering someone else about some other random code, which has a different problem than mine. :/
Edit to add more information:
There shouldn't be any problem with .Value or .get_Range, as it works on other parts of the code, but
For .Value, here is the information given by Visual Studio:
void Range.set_Value([object RangeValueDataType = System.Type.Missing], [object value = System.Type.Missing])
For .get_Range: Excel.Range_Worksheet.get_Range(object Cell1, [object Cell2 = System.Type.Missing])
For static, I still don't really understand all these "instances" things, but I will try to look more, and add another question in this forum if I still don't understand after this.
To your first question: I don't see any problem with your call of the method situation, maybe the problem is the statement inside the method (get_Range("C11"))?
To your second question: When you make a variable/property/method static it means that it is independent from any instance (object) of the class. Otherwise you couldn't access the property PPE_Process.pageTitre without an instance of PPE_Process.
Alrighty, I changed nothing in my code but now it works with
private void SituationEditBox_TextChanged(object sender, RibbonControlEventArgs e)
{
PPE_Process.pageTitre.situation = SituationEditBox.Text;
}
So... I don't know, it was maybe a problem with the build of my solution, but that's pretty fortunate :)

Get series name from HitTestResult on a data point and/or legend object; c# Visual Studio 2010

I'm trying to retrieve the series name from a mouse-click event in a Chart. I've looked through the documentation, including HitTestResult Class, from which I've gathered that I should be able to get the series using HitTestResult.Series.
When I try this, I get "An object reference is required for the non-static field, ..." error. While I understand (albeit a cursory understanding) what this error is referring to, mostly from responses to questions of other folks here on stackoverflow, I'm at a loss as to what's going on in my code.
Note: When I'm typing "HitTestResult.", Series is not an option in the IntelliSense; instead the only two options are Equals and ReferenceEquals.
Any thoughts or insights are appreciated. Thanks!!
Sample code:
private void myChart_MouseClick(object sender, MouseEventArgs e)
{
HitTestResult seriesHit = myChart.HitTest(e.X, e.Y);
if (seriesHit.ChartElementType == ChartElementType.DataPoint)
{
MessageBox.Show("Selected by Series!");
// ^^ This, as a test box, works fine...
parameterNameStr = HitTestResult.Series.Name;
// ^^ This is what I want but is causing trouble!
}
else if (seriesHit.ChartElementType == ChartElementType.LegendItem)
{
MessageBox.Show("Selected by Legend!!");
}
else
{
MessageBox.Show("Whoops, try again!");
}
}
Silly me. I was right there, just not thinking...
Here's what worked:
[...]
parameterNameStr = seriesHit.Series.Name;
// ^^^^^ Simple fix!!
[...]

get and Set not working

I am writing the following get and set for validating an input from a Text Box. Basically it is supposed to check if the user has entered all of the values.
When I leave the TextBoxes empty , it does nothing and shows a '0' in output where that variable was being used. It does however show the system generated exception and stops the execution, but I wonder why doesn't it validate the input through the properties?
Here is my code:
public double RecoDoseSize
{
get
{
return recoDoseSize;
}
set
{
if (!(value>0))
{
MessageBox.Show("Please Enter the recommended dose size for this product");
textBox8.Focus();
}
recoDoseSize = value;
}
}
private void Submit2_Click(object sender, RoutedEventArgs e)
{
TotalContentProduct = double.Parse(textBox7.Text);
recoDoseSize = double.Parse(textBox8.Text);
NoOfDosespUnit = TotalContentProduct/recoDoseSize;
}
You are setting recoDoseSize, the backing field, not RecoDoseSize, the property which has your code in it. Thus, your code isn't executed. You need to change the second line of your method body to
RecoDoseSize = double.Parse(textBox8.Text);
(note the capital R).
Other have given the correct answer to the question as stated. Namely that you should call the uppercased RecoDoseSize if you want to use the getter/setter.
However it is extremely bad practice to show a message box inside the setter, because it violates the Principle of Least Surprise.
When someone looks at the line RecoDoseSize = double.Parse(textBox8.Text); it is not at all obvious that this operation could cause a message box to appear.
There are occasionally exceptions where it does make sense to have a setter trigger UI changes (for instance the Visible property on controls) however the default should always be to not do this unless you are sure it will be more confusing to not do so (for instance it would be surprising if you set Visible = false however it was still visible).
Regarding your comment on how you should implement it, the checking should be done in the click handler and the property can just be an auto-property, like so:
public double RecoDoseSize { get; set; }
private void Submit2_Click(object sender, RoutedEventArgs e)
{
TotalContentProduct = double.Parse(textBox7.Text);
double enteredSize;
if (!double.TryParse(textBox8.Text, out enteredSize) || enteredSize <= 0)
{
MessageBox.Show("Please Enter the recommended dose size for this product");
textBox8.Focus();
return;
}
RecoDoseSize = enteredSize;
NoOfDosespUnit = TotalContentProduct / recoDoseSize;
}
You'll want to use TryParse because with Parse you'll get an error if the text isn't a valid double. What TryParse does is return true or false depending on whether it succeeded, and it populates the out parameter with the result if it's successful.
So what this does is if it either failed to parse the result, or the result is <= 0 it shows the message box. In that case it also returns from the method so the rest of it isn't executed. Alternatively the rest of the method could be in an else block in which case the return isn't needed. It's a matter a style which way is preferred.
You're never actually using the getter/setter. You are using the actual field name: recoDoseSize directly. Change it to RecoDoseSize.
private void Submit2_Click(object sender, RoutedEventArgs e)
{
TotalContentProduct = double.Parse(textBox7.Text);
RecoDoseSize= double.Parse(textBox8.Text);
NoOfDosespUnit = TotalContentProduct/recoDoseSize;
}
You shouldn't be handling focus in your set statement.
Also, you need to make sure that value is not null, otherwise you can't compare it to anything (greater-than, etc.).

How do I determine if the value of a string variable changed in C#?

I have something to do under a button click (add values to listbox) only if a particular string changes from its previous value. How do I manage this? Below is a sample of my code:
private void button6_Click(object sender, EventArgs e)
{
string x = //some varying value I get from other parts of my program
listBox1.Items.Clear();
listBox1.Items.Add(x + /*other things*/);
}
I can at times have same value for string x from previous value when clicking button6. In such cases I don't want listBox1 to add the item (string x). How to add to listbox only when value of string changes? There's no way to predetermine string x. It gets value when program is running.
Note: adding values to listBox1 every single time and later deleting the duplicates wont work in my program.
Have you considered keeping a copy of the old string value around in a private field, and simply comparing the new value to the old value to see if they match?
For example:
// holds a copy of the previous value for comparison purposes
private string oldString = string.Empty;
private void button6_Click(object sender, EventArgs e)
{
// Get the new string value
string newString = //some varying value I get from other parts of my program
// Compare the old string to the new one
if (oldString != newString)
{
// The string values are different, so update the ListBox
listBox1.Items.Clear();
listBox1.Items.Add(x + /*other things*/);
}
// Save the new value back into the temporary variable
oldString = newString;
}
Edit: As the other answers suggest, there are certainly other, more complicated solutions, like encapsulating all access to the string value in a property, or wrapping the string in a custom class. Some of these alternatives have the potential to be "cleaner", more object-oriented approaches. But they're all more complicated than simply saving the previous value in a field. It's up to you to decide whether your specific use case merits the complicated solution, or a simpler one. Think about long-term maintainability, not what's easier for you to implement right now.
string last = string.Empty;
private void button6_Click(object sender, EventArgs e)
{
string x = //some varying value I get from other parts of my program
if(x!=last)
{
listBox1.Items.Clear();
listBox1.Items.Add(x + /*other things*/);
last = x;
}
}
If this string is super important and gets passed around alot, maybe you should wrap it in a class. The class can hold the string value as a property, but also keep track of when it has changed.
public class StringValue
{
private bool _changed;
public string StrValue{get; set{ _changed = true;}
public bool Changed{get;set;}
}
this is rudimentery of course
I'm not sure I understand completely, but it sounds like you should be using a property to set String x;
string _x = string.Empty;
public string X
{
set
{
if(value != this._x)
{
DoFancyListBoxWork();
this._x = value;
}
}
get
{
return this._x;
}
}
If this is web application, store your last value into session variable. If this is windows application, store it at a class level variable or in singleton class and use this last value for comparison with new value.
On the page load add the current value to viewstate and at the button click check the current value is equal to the value in the view state. If both are equal we can say that the value is not changed.
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
ViewState["CurrentValue"] = Your Value;
}
}
protected void btnSubmit_click(object sender, EventArgs e)
{
if (NewValue== ViewState["CurrentValue"].ToString())
{
lblmsg.Text = "value is not changed..";
return;
}
else
lblmsg.Text = "value is changed..";
}
You can check the detailed article in this link.
Check Control Value is changed or not
First, I'd like to ask you to check most of the other answers. They are more complete, in that they treat more global issues of tracking the changes of a variable.
Now, I'm assuming, from reading the snippet of code you provided, that you need to track if a string was changed by the user. So, in other words, you probably have a TextBox or other kind of control through which the user can change that value. This is where you should focus your attention: just consume the TextChanged event.
If, however, I'm mistaken and your string comes from any other kind of external source, either use the wrapper class suggested by #Ryan Bennett or, if you are using .Net 4, use a dynamic container, which raises a PropertyChanged event whenever any property is changed.

C# and Winforms TextBox control: How do I get the text change?

I have an event handler for the TextBox.TextChanged event on a form of mine. In order to support undo, I'd like to figure out exactly what has changed in the TextBox, so that I can undo the change if the user asks for it. (I know the builtin textbox supports undo, but I'd like to have a single undo stack for the whole application)
Is there a reasonable way to do that? If not, is there a better way of supporting such an undo feature?
EDIT: Something like the following seems to work -- are there any better ideas? (It's times like this that I really wish .NET had something like the STL's std::mismatch algorithm...
class TextModification
{
private string _OldValue;
public string OldValue
{
get
{
return _OldValue;
}
}
private string _NewValue;
public string NewValue
{
get
{
return _NewValue;
}
}
private int _Position;
public int Position
{
get
{
return _Position;
}
}
public TextModification(string oldValue, string newValue, int position)
{
_OldValue = oldValue;
_NewValue = newValue;
_Position = position;
}
public void RevertTextbox(System.Windows.Forms.TextBox tb)
{
tb.Text = tb.Text.Substring(0, Position) + OldValue + tb.Text.Substring(Position + NewValue.Length);
}
}
private Stack<TextModification> changes = new Stack<TextModification>();
private string OldTBText = "";
private bool undoing = false;
private void Undoit()
{
if (changes.Count == 0)
return;
undoing = true;
changes.Pop().RevertTextbox(tbFilter);
OldTBText = tbFilter.Text;
undoing = false;
}
private void UpdateUndoStatus(TextBox caller)
{
int changeStartLocation = 0;
int changeEndTBLocation = caller.Text.Length;
int changeEndOldLocation = OldTBText.Length;
while (changeStartLocation < Math.Min(changeEndOldLocation, changeEndTBLocation) &&
caller.Text[changeStartLocation] == OldTBText[changeStartLocation])
changeStartLocation++;
while (changeEndTBLocation > 1 && changeEndOldLocation > 1 &&
caller.Text[changeEndTBLocation-1] == OldTBText[changeEndOldLocation-1])
{
changeEndTBLocation--;
changeEndOldLocation--;
}
changes.Push(new TextModification(
OldTBText.Substring(changeStartLocation, changeEndOldLocation - changeStartLocation),
caller.Text.Substring(changeStartLocation, changeEndTBLocation - changeStartLocation),
changeStartLocation));
OldTBText = caller.Text;
}
private void tbFilter_TextChanged(object sender, EventArgs e)
{
if (!undoing)
UpdateUndoStatus((TextBox)sender);
}
You might be better off using the Enter and Leave events instead. When entering, store the current text in a class variable, then when leaving compare the new text to the old.
Yes, don't tie it directly to the textbox. Your forms' state should be in some model object somewhere that isn't directly tied to the form (MVC is one way to do this, MVVM is another). By decoupling them like that, you can compare the new textbox value to the current model value whenever a change request comes in.
Actually, all I can think of is having some kind of collection where you store different string versions (so you can undo many times, not just once).
I would store the reference to TextBox's collections in TextBox.Tag, so it is straightforward to store/use it.
Last but not least, you update your collection of strings during the event TextChange. With no much work, you can maintain a full history, gettinjg the previous value from your own structure.
This is probably overkill for what you're trying to accomplish, but CSLA support n-level undo. CSLA is a great business objects framework written by Rocky Lhotka. The business objects handle the undo history and it flows to the UI through data binding.
Switching your app to use CSLA would be a big commitment, but another option would be to look through the freely available source code to see how he implemented it.
I am actually making an own Syntax-Highlight-System so I also need to know the changed text.
My solution is to watch for an enter or space or an depositioning of the cursor.
As WinForms provide the Keydown event I used the KeyEventArguments (e) and converted them to a char.
After that I storage the char into a string like :
string i="";
i+=convertedToChar; // convertedToChar = kc.ConvertToString(e.KeyData)
And as soon as there is a enter or space or depositioning - "event" I delete the string.
Result:
If a user enters a few chars and hit space I am able to read the last chars (till the last space).
An advantage would be the fact that you can use any delimiter char for that (as soon as they are storaged and provided by e.KeyCode)
However I hope that this is a solution for everybody watching this after 9years :D.
It´s never too late.

Categories