Creating a Search button with regex - c#

So I'm basically trying to create a search button.
This search is using REGEX.
I think I have it correct but it's not working, Can someone tell me how / where i've gone wrong, Not coded in AGES...
public void SearchFunction(string searchtext)
{
SupporterId();
ReferenceNumber();
ConsignmentNumber();
}
private static void SupporterId()
{
const string sId= "";
var supporterId = Regex.IsMatch(sId, #"^[A-F,S,R][0-9]{3,6}$", RegexOptions.IgnoreCase);
}
private static void ReferenceNumber()
{
const string refNumber = "";
var referenceNumber = Regex.IsMatch(refNumber, #"^[ABN158][0-9]{6,17}$", RegexOptions.IgnoreCase);
}
private static void ConsignmentNumber()
{
const string conNumber = "";
var consignmentNumber = Regex.IsMatch(conNumber, #"&[0-9]{14}$", RegexOptions.IgnoreCase);
}
}
}
Those are my Regex, And this is my code behind..
protected void CheckStateClick(object sender, EventArgs e)
{
ConsignmentSearch();
}
private void ConsignmentSearch()
{
var searchclass = new RegexMethods();
searchclass.SearchFunction(txtReferenceNumber.Text);
}
Can anyone tell me where I have gone wrong and HOW I can fix it, Please don't tell me oh your missing this an then don't tell me how to fix it.
IF you can tell me how / what needs adding to be fixed example: add this line of code here .... < >
Please and thank you.
__
THIS IS THE ERROR
Test 'M:DeliveryInputSystem.Default.AddBox_Click(System.Object,System.EventArgs)' failed: Object reference not set to an instance of an object.
System.NullReferenceException: Object reference not set to an instance of an object.
Default.aspx.cs(113,0): at DeliveryInputSystem.Default.AddBox_Click(Object sender, EventArgs e)

I may be wrong, but it looks like you are only checking empty strings...
How about checking your searchtext like this:
public void SearchFunction(string searchtext)
{
SupporterId(searchtext);
ReferenceNumber(searchtext);
ConsignmentNumber(searchtext);
}
private static void SupporterId(string sId)
{
var supporterId = Regex.IsMatch(sId, #"^[A-F,S,R][0-9]{3,6}$", RegexOptions.IgnoreCase);
}
private static void ReferenceNumber(string refNumber)
{
var referenceNumber = Regex.IsMatch(refNumber, #"^[ABN158][0-9]{6,17}$", RegexOptions.IgnoreCase);
}
private static void ConsignmentNumber(string conNumber)
{
var consignmentNumber = Regex.IsMatch(conNumber, #"&[0-9]{14}$", RegexOptions.IgnoreCase);
}
However, if I understand your code correctly, your searchtext variable only contains the txtReferenceNumber.Text text, so you should only run the ReferenceNumber(string searchtext) method on it.

You provided error text:
__ THIS IS THE ERROR Test'
M:DeliveryInputSystem.Default.AddBox_Click(System.Object,System.EventArgs)' failed:
Object reference not set to an instance of an object.
System.NullReferenceException:
Object reference not set to an instance of an object.
Default.aspx.cs(113,0): at DeliveryInputSystem.Default.AddBox_Click(Object sender, EventArgs e)
There is written cause of error: NullReferenceException and where does it occur Default.aspx.cs(113,0). You need to analyze what is there, in line 113 in Default.aspx.cs and why may it cause NullReferenceException.
If you don't know where to start, start with documentation. According to MSDN documentation for NullReferenceException class:
A NullReferenceException exception is thrown when you try to access a member on a type whose value is null.
You have often also an example there:
1: List<String> names;
2: if (sth) names = new List<String>();
3: names.Add("Major Major Major")
If sth is false then no instance is assigned to names and exception will be thrown.

Related

xamarin Essentials: No overload for > 'OnMainDisplayInfoChanged' matches delegate > 'EventHandler<DisplayInfoChangedEventArgs>'

I am following a Xamarin Example with my code:
public App()
{
InitializeComponent();
DeviceDisplay.MainDisplayInfoChanged += OnMainDisplayInfoChanged;
}
void OnMainDisplayInfoChanged(DisplayInfoChangedEventArgs e)
{
var displayInfo = e.DisplayInfo;
}
As far as I can see this is just the same as in this example:
https://learn.microsoft.com/en-us/xamarin/essentials/device-display?context=xamarin%2Fios&tabs=uwp
But it is giving me the error message:
App.xaml.cs(13,13): Error CS0123: No overload for
'OnMainDisplayInfoChanged' matches delegate
'EventHandler' (CS0123)
Can anyone help explain to me what this error message means and let me know if there is a way for me to fix this?
This error is coming because you missing first param that is object sender. Try to pass full method signature.
private void OnMainDisplayInfoChanged(object sender, DisplayInfoChangedEventArgs e)
{
var displayInfo = e.DisplayInfo;
}

How do I call a method with a reference to the class parameter?

So I've been trying to figure out how to get my code to work all night. I've been reading up on all kinds of stuff and trying to identify what I'm doing wrong, but everything I try I end up at the same issue. I'm trying to change a variable in my class by referencing it in a method so it will change in the class and not just locally. But I don't know what to put as a parameter for the ref Storyboard SB. Can someone tell me what should be done, I've tried setting it to null, even through a variable and it doesn't work. Also 'StoryBoard' is the class that I'm writing the code in.
public class StoryBoard
{
public string[] TextBoxes = new string[10];
public int Counter = 0;
private void RtClickButton_Click(object sender, EventArgs e)
{
RtClickButton_ClickImpl(sender, e, "what would I put here?");
}
private void RtClickButton_ClickImpl(object sender, EventArgs e, ref StoryBoard SB)
{
string TBT = TxtBox.Text;
switch(Counter)
{
case 0:
TextBoxes[Counter] = TBT;
break;
}
SB.Counter++; // Adds 1 to the counter.
LtClickButton.Enabled = true;
TxtBox.Clear(); // Clears the text box.
}
}
Try simply
Counter++;
or if in doubt you can use the this keyword to refer to instance members of this class, e.g
this.Counter++; // Adds 1 to the counter.
To expand upon this, all variables from the current object will always be accessible in a normal method (i.e. not static) unless a variable of the same name exists in the same scope, where the scope can be the method or a single block between curly braces.
If you use the this keyword it will always reference the variable that belongs to the object/class and not an inline variable that is defined in a different scope.
But I don't know what to put as a parameter for the ref Storyboard SB.
Keep a private member variable for SB:
private StoryBoard _SB = null; //A member variable to hold the StoryBoard object
public class Form1WhatEver
{
public Form1WhatEver()
{
//Instantiate a reference to the StoryBoard and hold it in the private member variable
_SB = new StoryBoard();
}
public string[] TextBoxes = new string[10];
public int Counter = 0;
private void RtClickButton_Click(object sender, EventArgs e)
{
RtClickButton_ClickImpl(sender, e, ref _SB); //Pass the instance of StoryBoard byRef.
//Check that our _SB Counter variable was incremented (+1)
System.Diagnostics.Debug.WriteLine(_SB.Counter.ToString());
}
private void RtClickButton_ClickImpl(object sender, EventArgs e, ref StoryBoard SB)
{
string TBT = TxtBox.Text;
switch(Counter)
{
case 0:
TextBoxes[Counter] = TBT;
break;
}
SB.Counter++; // Adds 1 to the counter.
LtClickButton.Enabled = true;
TxtBox.Clear(); // Clears the text box.
}

c# NullReferenceException but everything looks ok

i'm working on a school project and I got this error: NullReferenceException was unhandled by user code
Code:
private MazeGen mazeGen;
private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
{
object[] args = e.Argument as object[];
int value = (int)args[0];
bool solving = (bool)args[1];
if (!solving)
{
this.mazeGen.generateMaze(this.box.Width / value,
(this.box.Height - value) / value);
}
else
{
this.mazeGen.solve();
this.hasSolution = true;
}
this.box.Invalidate();
}
So the error occurs in this part: "this.mazeGen.generateMaze(this.box.Width / value,
(this.box.Height - value) / value);"
The object mazeGen is nog an object. I already checked everything and the class mazeGen is also public so I really don't understand why the program can't find mazeGen. Also I checked if value, width and height had a value and they did.
Maybe it's a stupid solution but I really have no idea what it could be.
Simply, you are not initializing the mazeGen, so it's null.
private MazeGen mazeGen = new MazeGen();

Null reference in C# Mono / GTK#

I am trying to create a simple note-taking application for my own use. The idea is to learn C#/Mono XML editing.
I can't find a NullReference that the compiler is complaining about. No idea why. I can't see it. After few days of searching I give up... help. :)
Here is the code that is making a bug. The application runs fine until I press a button to Add new note. It just crashes. The add_activated function runs when a button is pressed and it should use AddNote function.
The code is incomplete and it certainly has some logic bugs. But I can handle those. I'm just wondering why it won't run.
MainActivity.cs:
// (...)
protected void add_activated (object sender, System.EventArgs e)
{
Gtk.TextBuffer buffer;
buffer = textview1.Buffer;
Note note = new Note(entry3.Text, buffer.Text);
AddNote (note);
}
public static void AddNote (Note note)
{
string xmlFile = "/home/tomasz/.keeper/keeper.xml";
XmlDocument xmlDoc = new XmlDocument ();
xmlDoc.Load (xmlFile);
XmlNode xmlRoot = xmlDoc.CreateElement("keeper");
if (!xmlDoc.DocumentElement.Name.Equals("keeper") )
{
xmlDoc.AppendChild (xmlRoot);
}
XmlNode xmlNote = xmlDoc.CreateElement ("note");
XmlNode xmlTitle = xmlDoc.CreateElement ("title");
XmlNode xmlText = xmlDoc.CreateElement ("text");
xmlRoot.InsertAfter (xmlRoot.LastChild, xmlNote);
xmlTitle.InnerText = note.Title;
xmlNote.InsertAfter (xmlNote.LastChild, xmlTitle);
xmlText.InnerText = note.Text;
xmlNote.InsertAfter (xmlNote.LastChild, xmlText);
xmlDoc.Save (xmlFile);
}
protected void remove_activated (object sender, System.EventArgs e)
{
throw new System.NotImplementedException ();
}
}
}
Note.cs:
using System;
namespace Keeper
{
public class Note
{
private string title;
private string text;
public string Title {
get
{
return this.title;
}
set
{
this.title = value;
}
}
public string Text
{
get
{
return this.text;
}
set
{
this.text = value;
}
}
public Note (string title, string text)
{
this.Title = title;
this.Text = text;
}
}
}
The immediate problem is that you got the arguments to InserAfter mixed up. First one should be the node to insert and the second one should be the reference node. The root element has no children yet, so LastChild is going to be null and hence the exeption. Using null as a reference point is valid, but not as a node to add.
There are other issues but you said you are able to fix those, so there you go.

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.

Categories