Well I was trying to assign global variable to read values from Check boxes and radio buttons but the values don't update when the selections are changed ! Where have I done wrong? Here's the code:
private void chkInMut_Checked(object sender, RoutedEventArgs e)
{
GlobalVar.Mutate = 1;
}
private void chkShwCal_Checked(object sender, RoutedEventArgs e)
{
GlobalVar.ShowCal = 1;
}
private void chkOutSol_Checked(object sender, RoutedEventArgs e)
{
GlobalVar.OutCal = 1;
}
}
public static class GlobalVar
{
static int _MaxMin, _MutVal, _CalShow, _CalOut;
/// <summary>
/// Access routine for global variable.
/// </summary>
public static int Extrema
{
get
{
return _MaxMin;
}
set
{
_MaxMin = value;
}
}
public static int Mutate
{
get
{
return _MutVal;
}
set
{
_MutVal = value;
}
}
public static int ShowCal
{
get
{
return _CalShow;
}
set
{
_CalShow = value;
}
}
public static int OutCal
{
get
{
return _CalOut;
}
set
{
_CalOut = value;
}
}
}
when I try to print the numbers using this test satement, the values returned are unexpected :
maxMin = GlobalVar.Extrema;
calShow = GlobalVar.ShowCal;
calOut = GlobalVar.OutCal;
IsMutble = GlobalVar.Mutate;
txtOutput.Text += Convert.ToString("\nMaxima Minima"+maxMin+"\n"+"Show Cal : "+calShow+"\n"+"Output Cal :"+calOut+"\n"+"Mutate : "+IsMutble+"\n---------\n");
And when I check/un-check the boxes, the values are not updated as it should be. Where have I gone wrong?
Edit: Solved by adding Unchecked Parameter.
Probably you should write your event handlers like this
private void chkInMut_Checked(object sender, RoutedEventArgs e)
{
GlobalVar.Mutate = (chkInMut.IsChecked ? 1 : 0);
}
and so on .....
I think the problem is with your public static properties. for example try this:
public static int Extrema
{
get
{
return GlobalVar._MaxMin;
}
set
{
GlobalVar._MaxMin = value;
}
}
and do the same for all other properties.
Edit:
and why are you using this stucture? You can set your static class to be like this:
public static class GlobalVar
{
public static int Extrema;
public static int Mutate;
public static int ShowCal;
}
Related
Using C# 5.0, I'm creating a publish/subscribe relationship on a static field, so that I can access it from multiple pages. In the host window, I have
public enum PLCStates
{
Good,
Bad,
Disabled
};
public static class PLCSafeStates
{
public static event EventHandler testStates1Changed;
private static PLCStates _testStates1;
public static PLCStates testStates1
{
get { return _testStates1; }
set
{
if (value != _testStates1)
{
_testStates1 = value;
if (testStates1Changed != null)
testStates1Changed(null, EventArgs.Empty);
}
}
}
}
And then in the pages hosted by the window, I have things like:
public FB1()
{
InitializeComponent();
SafteyFaults.PLCSafeStates.testStates1Changed += PLCSafeStates_testStates1Changed;
}
private void PLCSafeStates_testStates1Changed(object sender, EventArgs e)
{
var test2 = SafteyFaults.PLCSafeStates.testStates1;
if (test2 == SafteyFaults.PLCStates.Bad)
{
VisualStateManager.GoToState(btnFB, "PLCBad", true);
}
if (test2 == SafteyFaults.PLCStates.Good)
{
VisualStateManager.GoToState(btnFB, "PLCGood", false);
}
}
private void btnFB_Click(object sender, RoutedEventArgs e)
{
VisualStateManager.GoToState(btnOut1, "PLCBad",false);
if (SafteyFaults.PLCSafeStates.testStates1 == SafteyFaults.PLCStates.Good)
SafteyFaults.PLCSafeStates.testStates1=SafteyFaults.PLCStates.Bad;
else
SafteyFaults.PLCSafeStates.testStates1 = SafteyFaults.PLCStates.Good;
}
(right now, I don't have any business logic wired up yet- once I get this working, I'll link to actual data).
Anyhow, all of this works to create a single field I can subscribe to, modify, etc. But I need 20+ of these fields. I want to make 'testStates1' an array, but I've not been able to get it to work.
If I make the following edits to the code shown so far, it compiles and runs, but throws an error when I actually try to access the field (e.g. click on the button to change it):
//window
public static class PLCSafeStates
{
public static event EventHandler testStates1Changed;
private static PLCStates[] _testStates1;
public static PLCStates[] testStates1
{
get { return _testStates1; }
set
{
if (value != _testStates1)
{
_testStates1 = value;
if (testStates1Changed != null)
testStates1Changed(null, EventArgs.Empty);
}
}
}
}
//page
public FB1()
{
InitializeComponent();
SafteyFaults.PLCSafeStates.testStates1Changed += PLCSafeStates_testStates1Changed;
}
private void PLCSafeStates_testStates1Changed(object sender, EventArgs e)
{
var test2 = SafteyFaults.PLCSafeStates.testStates1[0];
if (test2 == SafteyFaults.PLCStates.Bad)
{
VisualStateManager.GoToState(btnFB, "PLCBad", true);
}
if (test2 == SafteyFaults.PLCStates.Good)
{
VisualStateManager.GoToState(btnFB, "PLCGood", false);
}
}
private void btnFB_Click(object sender, RoutedEventArgs e)
{
VisualStateManager.GoToState(btnOut1, "PLCBad",false);
if (SafteyFaults.PLCSafeStates.testStates1[0] == SafteyFaults.PLCStates.Good)
SafteyFaults.PLCSafeStates.testStates1[0]=SafteyFaults.PLCStates.Bad;
else
SafteyFaults.PLCSafeStates.testStates1[0] = SafteyFaults.PLCStates.Good;
}
This is my class:
class EmpDetails
{
private string _EmpName;
private int _EmpID;
private string _EmpDepartment;
private string _EmpPosition;
public string EmpName
{
get
{
return _EmpName;
}
set
{
_EmpName = value;
}
}
public int EmpID
{
get
{
return _EmpID;
}
set
{
_EmpID = value;
}
}
public string EmpDepartment
{
get
{
return _EmpDepartment;
}
set
{
_EmpDepartment = value;
}
}
public string EmpPosition
{
get
{
return _EmpPosition;
}
set
{
_EmpPosition = value;
}
}
}
}
Following is my form:
public partial class Form1 : Form
{
EmpDetails d = new EmpDetails();
public Form1()
{
InitializeComponent();
}
private void btnSet_Click(object sender, EventArgs e)
{
d.EmpName = txtName.Text;
d.EmpID = Convert.ToInt32(txtID.Text);
d.EmpDepartment = txtDepartment.Text;
d.EmpPosition = txtPosition.Text;
}
private void btnClear_Click(object sender, EventArgs e)
{
txtName.Clear();
txtID.Clear();
txtDepartment.Clear();
txtPosition.Clear();
}
private void btnGet_Click(object sender, EventArgs e)
{
txtName.Text = d.EmpName;
txtID.Text = Convert.ToString(d.EmpID);
txtDepartment.Text = d.EmpDepartment;
txtPosition.Text = d.EmpPosition;
}
}
}
I am setting the values using text boxes in form so that the values go
in to properties I have created in class.
I'm getting error like: EncapsulationAssignmentCSharp.EmpDetails
does not contain a definition for GetEmpName and no extension
method GetEmpName accepting a first argument of type
EncapsulationAssignmentCSharp.EmpDetails could be found (are you
missing a using directive or an assembly reference?
I am guessing that I have to create a constructor with parameters and
set the values using keyword this, but I'm not sure how to pass the
values to the constructor. Please help me I am not very good with
programming.
Debug and run the code and check whether your code is calling GetEmpName
I have the a class in my application. It has been bound to winform textbox controls. But the textbox which is bound to BookingNo property, always shows zero (0). But i want the textbox keep empty. Is there any way to do it? Here is my code snippet.
public class Booking
{
private int pBookingNo;
private string pCustomerName;
private string pAddress;
public int BookingNo
{
get { return pBookingNo; }
set
{
if (!value.Equals(pBookingNo))
{
pBookingNo = value;
}
}
}
public string CustomerName
{
get { return pCustomerName; }
set
{
if (!value.Equals(pCustomerName))
{
pCustomerName = value;
}
}
}
public Booking() { }
}
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
AddDataBindings();
}
private void AddDataBindings()
{
bsBooking.DataSource = typeof(Booking);
txtBookingNo.DataBindings.Add("Text", bsBooking, "BookingNo", true, DataSourceUpdateMode.OnPropertyChanged, null, "G", GlobalVariables.CurrentCultureInfo);
txtCustomerName.DataBindings.Add("Text", bsBooking, "CustomerName");
}
}
The default value of an Integer is 0, so you have to wrap it into some other object, which supports values other than 0, like
public int? BookingNo { get; set; }
You can use Nullable Type
public int? pBookingNo
{
get;
set;
}
Link : http://msdn.microsoft.com/fr-fr/library/1t3y8s4s(v=vs.80).aspx
You could use custom formatting for the binding by adding a handler to the Format event (http://msdn.microsoft.com/en-us/library/system.windows.forms.binding.format.aspx) and return an empty string when the value is zero. But you wouldn't be able to tell whether the value is actually zero or it just hasn't been set already, in which case using the int? approach suggested by #Grumbler85 is better.
what´s about:
textBox1.BindingContextChanged += new EventHandler(BindingContext_Changed);
private void BindingContext_Changed(object sender, EventArgs e)
{
TextBox txtBox = (TextBox)sender;
if (txtBox.Text == "0"){
txtBox.Text = "";
}
}
don´t know if it works, just an idea.
How can I implement in richTextBox something like filter (connected e.g. with combobox) that'll be responsible for showing only lines containing selected word (filters)?
I'm not talking about removing other lines - only "hide".
Is it possible?
Eventually I could use another type control, but if it's not neccessary I'd like to use richTextBox.
I thought now, about storing data in some structure, and make filtering based on this used structure. But don't know if it's efficient solution.
Try to make something like this
public string[] RtbFullText;
private void button7_Click(object sender, EventArgs e)
{
RtbFullText = richTextBox1.Text.Split('\n');
}
private void button8_Click(object sender, EventArgs e)
{
//Filter
richTextBox1.Text = "";
foreach (string _s in RtbFullText)
{
if (_s.Contains("Filter"))
richTextBox1.Text += _s + "\n";
}
}
So you can do this
public class NewRichTextBox : RichTextBox
{
public string[] TotalText;
private bool filter = false;
protected override void OnTextChanged(EventArgs e)
{
base.OnTextChanged(e);
if (!filter)
TotalText = Text.Split('\n');
}
public void Filter(string sf)
{
filter = true;
Text = "";
foreach (string _s in TotalText)
{
if (_s.Contains(sf))
Text += _s + "\n";
}
filter = false;
}
}
public Form1()
{
InitializeComponent();
NewRichTextBox myrtb = new NewRichTextBox();
myrtb.Name = "NRTB";
Controls.Add(myrtb);
}
private void button1_Click(object sender, EventArgs e)
{
NewRichTextBox mtrb = (NewRichTextBox)Controls.Find("NRTB", false)[0];
mtrb.Filter("Filter");
}
OMG i do it, use this class:
public class ListWithRTB : IList
{
private List<string> _contents = new List<string>();
private int _count;
string lastsearch = "";
public ListWithRTB()
{
_count = 0;
}
public object rtb;
private void UpdateRtb(string search)
{
lastsearch = search;
if (rtb is RichTextBox)
{
((RichTextBox)rtb).Text = "";
List<string> help_contents;
if (search != "")
help_contents = _contents.Where(s => s.Contains(search)).ToList();
else
help_contents = _contents;
for (int i = 0; i < help_contents.Count; i++)
{
((RichTextBox)rtb).Text += help_contents[i] + "\n";
}
}
}
public void Filter(string search)
{
UpdateRtb(search);
}
public int Add(object value)
{
if (_count < _contents.Count + 1)
{
_contents.Add((string)value);
_count++;
UpdateRtb(lastsearch);
return (_count);
}
else
{
return -1;
}
}
public void RemoveAt(int index)
{
_contents.RemoveAt(index);
_count--;
UpdateRtb(lastsearch);
}
public void Clear()
{
_contents.Clear();
UpdateRtb(lastsearch);
_count = 0;
}
public bool Contains(object value)
{
return _contents.Contains((string)value);
}
public int IndexOf(object value)
{
return _contents.IndexOf((string)value);
}
public void Insert(int index, object value)
{
_contents.Insert(index,(string) value);
_count++;
}
public bool IsFixedSize
{
get
{
return false;
}
}
public bool IsReadOnly
{
get
{
return false;
}
}
public void Remove(object value)
{
RemoveAt(IndexOf(value));
}
public object this[int index]
{
get
{
return _contents[index];
}
set
{
_contents[index] = value.ToString();
}
}
public void CopyTo(Array array, int index)
{
int j = index;
for (int i = 0; i < Count; i++)
{
array.SetValue(_contents[i], j);
j++;
}
}
public int Count
{
get
{
return _count;
}
}
public bool IsSynchronized
{
get
{
return false;
}
}
public object SyncRoot
{
get
{
return this;
}
}
public IEnumerator GetEnumerator()
{
throw new Exception("The method or operation is not implemented.");
}
public void PrintContents()
{
Console.WriteLine("List has a capacity of {0} and currently has {1} elements.", _contents.Count, _count);
Console.Write("List contents:");
for (int i = 0; i < Count; i++)
{
Console.Write(" {0}", _contents[i]);
}
Console.WriteLine();
}
}
And this how you can use it
ListWithRTB _mlrtb = new ListWithRTB();
private void button1_Click(object sender, EventArgs e)
{
_mlrtb.rtb = richTextBox1;
_mlrtb.Add("Filter");
_mlrtb.Add("123");
_mlrtb.Add("111 Filter");
}
private void button2_Click(object sender, EventArgs e)
{
_mlrtb.Filter("Filter");
}
private void button3_Click(object sender, EventArgs e)
{
_mlrtb.Filter("");
}
private void Button_Click(object sender, RoutedEventArgs e)
{
if (!string.IsNullOrEmpty(SearchableString) && !string.IsNullOrEmpty(FullRichtxt))
{
var SplitedTxt = FullRichtxt.Split('\n').ToList<string>();
List<string> filterlist = SplitedTxt.Where(x => x.Contains(contx.SearchableString)).ToList<string>();
string FilterString=string.Empty;
foreach(string str in filterlist)
{
FilterString+=str+"\n";
}
(RichTextBox1 as RichTextBox).AppendText(FilterString);
}
}
I know this has been a very old question however I ran into the same issue and implemented it which also retains any RTF formatting.
/// <summary>
/// This Control allows to filter the content of the RichTextBox by either manually
/// calling <c>ApplyFilter(string)</c> with the search string or specifying a TextBox Control
/// as a filter reference.
///
/// Matching lines will be retained, other will be deleted.
///
/// Retains RTF formatting and when removing the filter restores the original content.
///
/// Ideal for a Debug Console.
///
/// </summary>
public class RichFilterableTextBox : RichTextBox
{
private Timer timer;
private string OriginalRTF = null;
private TextBox _filterReference;
private int _interval = 2000;
public TextBox FilterReference
{
get => _filterReference;
set
{
//if we had already a filter reference
if (_filterReference != null)
{
//we should remove the event
_filterReference.TextChanged -= FilterChanged;
}
_filterReference = value;
//if our new filter reference is not null we need to register our event
if (_filterReference != null)
_filterReference.TextChanged += FilterChanged;
}
}
/// <summary>
/// After the filter has been entered into the FilerReference TextBox
/// this will auto apply the filter once the interval has been passed.
/// </summary>
public int Interval
{
get => _interval;
set
{
_interval = value;
timer.Interval = Interval;
}
}
public RichFilterableTextBox()
{
timer = new Timer();
timer.Interval = Interval;
timer.Tick += TimerIntervalTrigger;
}
public void SetFilterControl(TextBox textbox)
{
this.FilterReference = textbox;
}
public void ApplyFilter(string searchstring)
{
int startIndex = 0;
int offset = 0;
//check each line
foreach (var line in this.Lines)
{
offset = 0;
SelectionStart = startIndex + offset;
SelectionLength = line.Length + 1;
//if our line contains our search string/filter
if (line.Contains(searchstring))
{
//we apply an offset based on the line length
offset = line.Length;
}
else
{
//otherwise delete the line
SelectedText = "";
}
//move the start index forward based on the current selected text
startIndex += this.SelectedText.Length;
}
}
private void FilterChanged(object sender, EventArgs e)
{
//take snapshot of original
if (OriginalRTF == null)
{
OriginalRTF = this.Rtf;
}
else
{
//restore original
Rtf = OriginalRTF;
OriginalRTF = null;
}
timer.Stop();
timer.Start();
}
private void TimerIntervalTrigger(object sender, EventArgs e)
{
//stop the timer to avoid multiple triggers
timer.Stop();
//apply the filter
ApplyFilter(FilterReference.Text);
}
protected override void Dispose(bool disposing)
{
timer.Stop();
timer.Dispose();
base.Dispose(disposing);
}
}
This control can be either used standalone and be filter by calling the method
ApplyFilter(string searchString) with the desired search string. Or it can be connected to a TextBox
where you will be able to enter the phrase in. After a set timer interval it will auto trigger the filtering.
I am using this as a Log Display during runtime where I am also applying color codes to severity and my goal was to retain the formatting as well as be able to quickly search/filter. I attached a few screenshots:
There is still room for improvements and I hope this can be used as a starting code base.
Can I lock/unlock fields or objects at runtime against writing? In other words something like changing objects to read-only temporarily at runtime...
For example:
int x = 5; // x is 5
LockObject(x);
x = 7; // no change
UnlockObject(x);
x = 10; // x is 10
if not can you give me some possible solutions?
You can use accessors to do this...
public class X
{
private bool locked = false;
private int lockedVar;
public int LockedVar
{
get { return lockedVar; }
set { if (!locked) lockedVar = value; }
}
public void LockObject() { locked = true; }
public void UnlockObject() { locked = false; }
}
Wrap it in a property and then use a boolean flag as the "lock".
You can also use a struct to handle this type of logic.
public struct LockableInt
{
private int _value;
public bool Locked;
public void Lock(bool locked) {Locked = locked;}
public int Value
{
get
{ return _value; }
set
{ if (!Locked) _value = value; }
}
public override string ToString()
{
return _value.ToString();
}
}
Sample client code:
public static void RunSnippet()
{
LockableInt li = new LockableInt();
li.Value = 5;
Console.WriteLine(li.ToString());
li.Lock(true);
li.Value = 6;
Console.WriteLine(li.ToString());
li.Lock(false);
li.Value = 7;
Console.WriteLine(li.ToString());
}
Output:
5
5
7
Press any key to continue...
Thanks all for help. Here is a more generalized alternative.
I have decided that it would be more convenient to use freeze/unfreeze since lock/unlock exists in the context of multithreading programming.
public class FreezeableValue<T>
{
private bool frozen;
private T value;
public FreezeableValue()
{
frozen = false;
}
public FreezeableValue(T value)
{
this.value = value;
frozen = false;
}
public void Freeze(bool frozen)
{
this.frozen = frozen;
}
public T Value
{
get { return value; }
set
{
if (!frozen) this.value = value;
}
}
}