简体   繁体   中英

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

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

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM