Assign string to label Object in C# - c#

I have tried to assign a String to Label but i Cannot able assign to a Label Field
i have Attached my code with it
if (intAdditionalTestId == 16 || intAdditionalTestId == 24)
{
strControlName = "lblMGOSSC" + Convert.ToString(intAdditionalTestId).PadLeft(2, '0') + "01AddUpd";
DisplayMessage(strControlName.ToString().Trim());
lblField = (Label)Page.FindControl(strControlName);
if (lblField.Text.Contains("[ADD]"))
{
intUpdateFlag = 0;
}
else
{
intUpdateFlag = 1;
}
I want to store the value of strControlName to lblField
Error Message Displayed While Running the Code:
Insufficient stack to continue executing the program safely. This can happen from having too many functions on the call stack or function on the stack using too much stack space.

You are trying to find label using a string which you want to set to as label text. It is wrong.
You should change it;
lblField = (Label)Page.FindControl(strControlName);
to
lblField = (Label)Page.FindControl("lblField");//"ldlField" is ID of label"
lblField.Text = strControlName;

Related

How to set up a label default for first time application use

I have a label called totalChips. It gets the data from being saved so that the player can continue on where they left off. After the first debug the label is empty and then it isn't possible to add chips. I added a button to set the label to 0 but would like the label to be automatically set to zero if there is no value saved. This must be done when the form loads.
{
if (totalChips.Text == null)
{
totalChips.Text = "0";
Properties.Settings.Default.SaveCoins = totalChips.Text;
Properties.Settings.Default.Save();
}
else
{
totalChips.Text = Properties.Settings.Default.SaveCoins;
}
} ```
I used if (string.IsNullOrEmpty(totalChips.Text)) to set the first time launch is zero and afterwords the else is called and I just called the method to get the saved value before calling the if statement.
totalChips.Text = Properties.Settings.Default.SaveCoins;
EnableRedeem.Text = Properties.Settings.Default.SaveRedeem;
if (totalChips.Text == "")
{
totalChips.Text = "0";
Properties.Settings.Default.SaveCoins = totalChips.Text;
Properties.Settings.Default.Save();
}
else

How to open a textfile in XNA/monogame(beginner here)?

Okay, so i am working in xna and i want to open this textfile which should open in a textfile. Here is the code:
if (Keyboard.GetState().IsKeyDown(Keys.G) == true)
{
var fileToOpen = "Name.txt";
var process = new Process();
process.StartInfo = new ProcessStartInfo()
{
UseShellExecute = true,
FileName = fileToOpen
};
process.Start();
process.WaitForExit();
}
However an error occurs and cant find the textfile to open. I did this in a normal consol application and just added a new item textfile to the project and it worked fine in the console application, however in XNA it does not seem to work at all.
Also im really not well educated in file directory things and need a quick fix. The text files are placed in this area:
I hope this is of somehelp im trying to give as much information as possible. Just to note streamwriting to textfiles in the directory location shown in the image link works perfectly fine and i just give the name of the file as shown below:
if (player.GetRec.Intersects(map.sharkRec))
{
using (StreamWriter writer = new StreamWriter("CurrentScore.txt"))
{
writer.Write(time);
}
player.Position = new Vector2(64,100);
mCurrentScreen = ScreenState.leaderboard;
}
However it just didt seem to work when i want to open the textfile in notepad and allow for typing to be done in the textfile in notepad. The reason why i want to open a text file for typing is the user entering there name and i dont have knowledge or the time to do XNA textbox input creation which seems complicated from the tutorials i have seen, which is why i want to open the textfile in notepad for editing. Furthermore this is going to be used on other people's computers so if directorys have to be used i need a directory that will work on other computers as well as my own, just to note directory entering seems to confuse me.
Hope i have given enough information and i really hope someone can help this beginner out here :)
For this to work, your code should be something like this:
using(StreamWriter ...)
{
show textbox so the user can see what he's typing
for each keypress add the letter
exit on ESC button (for example)
delete char on Backspace
etc...
}
Now, I personaly don't recommend this type of code. Open the file, do what you have to do with it and close it. The code below is how I programmed textbox for my game. I hope it helps (you could say this is more a little tutoial for better approach to the problem instead an answer to the exact problem you put up for yourself).
namespace Acircalipse.MenuClasses
{
public class TextBox:MenuItem
{
private string originTitle;
public string Text
{
get
{
return title.Replace(originTitle, "").Replace(Menu.separator, "");
}
}
public int index, max;
public TextBox (string Title, string text = "", int MaxCharacters = 14)
{
originTitle = Title;
index = 0;
max = MaxCharacters;
SetText(text);
}
public void SetText (string text)
{
if (text.Length > max) text = text.Substring(0, max);
title = originTitle + Menu.separator + text;
}
public void ChangeIndex (int howMuch)
{
index += howMuch;
ChangeCar(index);
}
public void AddChar (int index = 0)
{
SetText(Text + Menu.Wheel(index));
}
public void ChangeCar (int index)
{
if(Text.Length > 0)
SetText(Text.Substring(0, Text.Length - 1) + Menu.Wheel(index));
}
public void DeleteChar ()
{
if (Text.Length > 0)
SetText(Text.Substring(0, Text.Length - 1));
}
}
}
Where the Menu.Wheel(int index) is simply an array of available character for user to type in
public static char Wheel(int index)
{
string charWheel = " ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
int max = charWheel.Length;
while (index > max) index -= max;
while (index ("less than" sign here) 0) index += max;
return charWheel[index];
}
Where Menu.separator is a string ": ".
The code is pretty self explanatory.
Now, when using this class, you'll have to have one bool to see if the user has activated this textbox, and if he has, add text on keypress. If the textbox is inactive, just continue your normal update
What you have to understand is that textbox is a simple string witch is updated when textbox is active, and just showed when not active.
Using this simple and on point definition of TextBox, you can simply create your own class that will work the way you want to.
If this answer helped you resolve your problem, please mark it as the solution.

Basic Counter for login c#

I'm stuck with a login counter to keep track on how many times someone has tried to login. (Failed attempts)
Im at VisionPro Designer from Cognex which uses C# and .NET.
When the maximum attempts is reached within the timeframe starting from the first failed attempt (let's say 5 minutes) the password box will be blocked.
I'm a beginner at programming, just self taught.
The current settings is just none, got a user database built-in the program.
A textbox for username and a passwordbox for the password (Obviously).
I set it up so when the passwordbox got a changed value it matches the credentials with the user database and if that's "true" you get to the advanced options page. And i dont want any non-trusted machine operators reaching the advanced settings page.
The program uses "Value Tags" that you can get the value or change the value wherever you are in the program, got a tag set up for the loginattempts "Tag_LoginCount"
Here's the passwordbox code:
if ($System.Users.Login($Tag_InputUsername, $Tag_InputPassword))
{
$Pages.MainPage.PasswordBox.Password = ""; //Resets the passwordbox password at login
$HMI.ShowPage("LidSettings"); //Opens the Lidsettings page
$Pages.LidSettings.Slider2.Value = 0; //Disables the advanced settings option
}
else
{
$Pages.MainPage.PasswordBox.Password = ""; //resets password
}
It looks like you've already got a tag called "Tag_LoginCount" defined. I presume it's an Integer. You can check existing tags and add new ones in the 'Tag Manager'.
I'd consider adding a few more tags:
FailedLogins (Integer)
TimeOfFirstLogin (DateTime)
UserLockedOut (Boolean)
UserLockoutStart (DateTime)
To use tags in the script, simply prefix the tag names with a dollar sign (e.g., $FailedLogins), or drag-and-drop them from the Toolbox to your script.
The script below should achieve something close to what you want:
const int USER_LOCKOUT_PERIOD = 10;
const int MAX_LOGIN_ATTEMPTS = 8;
const int LOGIN_TIMEFRAME = 5;
// Check if user is locked out
int minutesUserLockedOut = (int)DateTime.Now.Subtract($UserLockoutStart).TotalMinutes;
if ($UserLockedOut && (minutesUserLockedOut > USER_LOCKOUT_PERIOD))
{
$UserLockedOut = false;
}
if ($UserLockedOut)
{
int userLockoutMinutesRemaining = (int)(USER_LOCKOUT_PERIOD - minutesUserLockedOut);
$HMI.ShowMessage("Too many failed login attempts. System locked for " + userLockoutMinutesRemaining + " minutes.");
$Pages.MainPage.PasswordBox.Password = ""; //resets password
return;
}
// Reset number of failed logins if first failed login more than LOGIN_TIMEFRAME minutes ago
TimeSpan minutesSinceFirstBadLogin = (int)DateTime.Now.Subtract($TimeOfFirstBadLogin).TotalMinutes;
if (minutesSinceFirstBadLogin > LOGIN_TIMEFRAME)
{
$FailedLogins = 0;
}
if ($System.Users.Login($Tag_InputUsername, $Tag_InputPassword))
{
// Successful login! Reset number of bad logins
$FailedLogins = 0;
$HMI.ShowPage("LidSettings"); //Opens the Lidsettings page
$Pages.LidSettings.Slider2.Value = 0; //Disables the advanced settings option
}
else
{
// If this is the first failed login, record the time
if ($FailedLogins == 0)
{
$TimeOfFirstBadLogin = DateTime.Now;
}
// Increment the number of failed logins
$FailedLogins = $FailedLogins + 1;
// Lock the user out if the number of failed logins exceeds maximum allowed
if ($FailedLogins > MAX_LOGIN_ATTEMPTS)
{
$UserLockedOut = true;
$UserLockoutStart = DateTime.Now;
}
}
$Pages.MainPage.PasswordBox.Password = ""; //resets password
It's kind of hard to say what you might need here, given your description. I'll assume that the code snippet you presented is inside an event handler processing some user input. I'll put the event handler inside a class. To be able to preserve the value of a counter between multiple invocations of the handler, you need to store the value of the counter somewhere outside of the handler. One approach is to have a class level variable.
public class C
{
public C()
{
_counter = 0; // initialize the counter when creating a class instance
{
private int _counter;
private void Handler()
{
if (System.Users.Login(Tag_InputUsername, Tag_InputPassword))
{
Pages.MainPage.PasswordBox.Password = ""; //Resets the passwordbox password at login
HMI.ShowPage("LidSettings"); //Opens the Lidsettings page
Pages.LidSettings.Slider2.Value = 0; //Disables the advanced settings option
_counter++; // increment the counter field
}
else
{
Pages.MainPage.PasswordBox.Password = ""; //resets password
}
}
}
I presume that's not exactly what you want, because there is no distinction between a valid and invalid login attempt, but you should be able to figure out how to adapt the example.

ProcessBar counter C#

I have a question about the ProcessBar on C#,
How would I add the value of 1 to a label if the method used when passing an item within a list box was successful ?
I have a method like this
private static Form1 f1 = Application.OpenForms["Form1"] as Form1;
public static void GroupList1(processBar bar)
{
f1.listBox1.Items.Add("User1");
bar.Value = 100;
}
public static void GroupList2(processBar bar2)
{
f1.listBox1.Items.Add("User2");
bar.Value = 100;
} // Etc, etc - up to GroupList6
I would also like to have a label that tells me how many user's were successfully added (using the bar), I was thinking of adding a method like this :
if (bar.Value = 100)
{
f1.label1.Text = "" + 1;
}
Inside of my GroupList1/2 method, but the label always appears as the value 1 .
This method within the main form of my code loads a separate label :
for(int i = 0; int i < listBox1.Items.Count; i++)
{
label2.Text = i.ToString();
}
So, I would like label 1 to increase by 1 if the user has been loaded into my list box successfully, how would I do this ?
Obviously this isn't actually the code I'm using within my program, a method is used if the selected index changes (which is why I want to increase by 1, to ensure the user parsed the method successfully), but the question still remains as described, thanks.
I dont quite understand well what are you trying to achieve, but if you only look in increasing the value of such label then you can easily do this by
if (bar.Value = 100)
{
f1.label1.Text = ""+(int.Parse(f1.label1.Text)+1);
}
or even a better way to initialize the string if for some reason the Text of the label is not an integer
if (bar.Value == 100)
{
int value;
if(!int.TryParse(f1.label1.Text,out value))
{
f1.label1.Text = "1";
}
else
{
f1.label1.Text = ""+(value+1);
}
}
but the best way to do this is to keep track of the value in a separate variable and just update the content of the label.
It's a bad idea to store the actual count in the label's Text property, instead, create a variable:
private static int count;
Now, change your code to something like this:
if (bar.Value = 100)
{
// Add 1
count += 1;
// Update the UI
f1.label1.Text = count.ToString();
}

Set focus back on a ComboBox if the value is incorrect

I am trying to set my ComboBoxes so that the user can either choose from the list or set their own value (the combo box is for a custom resolution so there will be default values or they can give their own).
I am trying to make it so that if their value is incorrect (below 0 or not an Int) then it shows a tooltip and prevents it from losing focus. Here is my code:
private void cmbX_Graphics_Width_LostFocus(object sender, EventArgs e)
{
int i = 0, width = 0;
TLQAShared._debug("Lost Focus Fired");
for (i = 0; i < cmbX_Graphics_Width.Items.Count; i++)
{
if (cmbX_Graphics_Width.Text.Equals(cmbX_Graphics_Width.Items[i].ToString()))
{
Properties.X.Default.Graphics_Width = int.Parse(cmbX_Graphics_Width.Items[i].ToString());
TLQAShared._debug("FOUND!");
return;
}
TLQAShared._debug("FOR: " + i.ToString() + "/" + (cmbX_Graphics_Width.Items.Count - 1).ToString() + ": " + cmbX_Graphics_Width.SelectedText + ":" + cmbX_Graphics_Width.Items[i].ToString());
}
TLQAShared._debug("Not true: '" + cmbX_Graphics_Width.Text + "'");
if (int.TryParse(cmbX_Graphics_Width.Text.ToString(), out width))
{
TLQAShared._debug("TryParse: true");
Properties.X.Default.Graphics_Width = width;
}
else
{
tt.SetToolTip(cmbX_Graphics_Width, "You must supply a valid integer");
this.ActiveControl = cmbX_Graphics_Width;
TLQAShared._debug("TryParse invalid.");
}
}
However if the control loses focus, this code gets executed twice, first time it stops at this part:
TLQAShared._debug("Not true: '" + cmbX_Graphics_Width.Text + "'");
Then does it again but executes the entire code, but does not prevent the control from losing focus.
Two questions I have:
Firstly: Is this the best practice and if not what should I do?
Secondly: If it is best practice, how would I fix it?
use combobox1.Select(); for focus in combobox.
I don't think this is a good practice. I would do it like this:
Create a function to check if the input is valid (int > 0)
Call this function when the user attempts to enter the input
If the input isn't valid call combobox.focus()

Categories