I'm trying to create an object in my windows form app but if I create it in the constructor, then I can't access it in the entire app...(Like the events) In the code below the Time1 isn't available. I'll be happy to hear from you...
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace ClockApp
{
public partial class ClockApp : Form
{
public ClockApp()
{
InitializeComponent();
ClockApp Time1 = new ClockApp();
}
private void textBox1_TextChanged(object sender, EventArgs e)
{
}
private void ClockApp_Load(object sender, EventArgs e)
{
}
private void btnOk_Click(object sender, EventArgs e)
{
//ClockApp Time1 = new ClockApp();
Time1.getHour = Convert.ToInt16(txtHour.Text);
Time1.getMin = Convert.ToInt16(txtMin.Text);
Time1.getSec = Convert.ToInt16(txtSec.Text);
if(rbUniversal.Checked == true)
{
Time1.ToUniversal();
}else if(rbStandard.Checked == true)
{
Time1.ToStandard();
}
else
{
lblTime.Text = "NOT Working...";
}
}
}
}
The code below is my class:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace ClockApp
{
public partial class ClockApp : Form
{
// Fields
private int Hour;
private int Min;
private int Sec;
// Properties
public int getHour
{
get
{
return Hour;
}
set
{
if(value > 23 && value < 0)
{
Hour = 23;
}
else
{
Hour = value;
}
}
}
public int getMin
{
get
{
return Min;
}
set
{
if(value > 59 && value < 0)
{
Min = 59;
}
else
{
Min = value;
}
}
}
public int getSec
{
get
{
return Sec;
}
set
{
if(value > 59 && value < 0)
{
Sec = 59;
}
else
{
Sec = value;
}
}
}
// Constructors
// Methods
// ToUniversal()
public void ToUniversal()
{
lblTime.Text = Hour.ToString() + ":" + Min.ToString() + ":" + Sec.ToString();
}
// ToStandard()
public void ToStandard()
{
if(Hour > 12)
{
int[] Modifier = new int[12];
for (int i = 0; i < 12; i++)
{
Modifier[i] = i + 13;
if (Hour == Modifier[i])
{
Hour = i+1;
lblAMPM.Text = "PM";
}
}
lblTime.Text = Hour.ToString() + ":" + Min.ToString() + ":" + Sec.ToString();
}
else
{
lblAMPM.Text = "AM";
lblTime.Text = Hour.ToString() + ":" + Min.ToString() + ":" + Sec.ToString();
}
}
}
}
You dont need to create a new instance of ClockApp in the constructor.
Remove that line.
The field (or whatever) 'Time1' is not needed. Remove 'Time1.' completely form your code:
Time1.getHour = Convert.ToInt16(txtHour.Text); => getHour = Convert.ToInt16(txtHour.Text);
Time1.ToUniversal(); => ToUniversal();
and so on.
That should make your code at least compilable.
Bugs:
value > 23 && value < 0 is always false. You have to use || instead of &&.
same for value > 59 && value < 0
Code conventions:
I know you just starting with c#, but please check the common coding convention to improve the readabilty:
Properties: first letter is capitalized
Fiels: first letter is not capitalized
Do not start you propery name with 'get'. Just Hour, Min or Sec is perfect.
Related
I have a program that is suppose to collect user car data in one method/class and then use it later.
In this case, user types in Year: 2001 Make: Mustang Model: GT (click Make the Car Button). The textboxes are cleared. Then click accelerate. In the DetailLabel it should increment speed by 5 every time the button is pressed. Output: The speed of 2001 Mustang GT is 5 mph. Same for the Brake Button. The speed of 2001 Mustang GT is 0 mph.
Problem: I can't access/use my collected data for brake or accelerate buttons.
Form1.cs:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace CarMaker_Tate
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void GetCarData()
{
CarClass myCar = new CarClass();
int CYear;
string CMake = MakeTextBox.Text;
String CModel = ModelTextBox.Text;
if (int.TryParse(YearTextBox.Text, out CYear) && CYear >= 1900 && CYear <= 2022)
{
if (CMake != "")
{
if (CModel != "")
{
myCar.Year = CYear;
myCar.Make = CMake;
myCar.Model = CModel;
}
else
MessageBox.Show("Please enter a car model");
}
else
MessageBox.Show("Please enter a car make");
}
else
MessageBox.Show("Please enter a year between 1900 - 2022");
}
private void MakeButton_Click(object sender, EventArgs e)
{
GetCarData();
YearTextBox.Text = "";
MakeTextBox.Text = "";
ModelTextBox.Text = "";
}
private void AccelerateButton_Click(object sender, EventArgs e)
{
myCar.AccSpeed(5);
DetailLabel.Text = "The speed of " + myCar.Year + myCar.Make + myCar.Model + "is" + myCar.Speed + "mph";
}
private void Summarybutton_Click(object sender, EventArgs e)
{
Summary mySummaryForm = new Summary();
mySummaryForm.Show();
}
private void BrakeButton_Click(object sender, EventArgs e)
{
myCar.DecSpeed(5);
DetailLabel.Text = "The speed of " + myCar.Year + myCar.Make + myCar.Model + "is" + myCar.Speed + "mph";
}
}
}
CarClass.cs:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace CarMaker_Tate
{
class CarClass
{
int CarYear;
string CarMake;
string CarModel;
public static int CarCount;
public CarClass()
{
// constructor runs everytime a car is created
CarYear = 0;
CarMake = "";
CarModel = "";
CarCount++;
}
public int Year
{
get
{
return CarYear;
}
set
{
CarYear = value;
}
}
public string Make
{
get { return CarMake; }
set { CarMake = value; }
}
public string Model
{
get { return CarModel; }
set { CarModel = value; }
}
public int Speed
{
get { return Speed; }
set { Speed = value; }
}
public void AccSpeed(int speedIncrement)
{
//Add check for speed limit ranges
Speed += speedIncrement;
}
public void DecSpeed(int speedDecrement)
{
//Add check for speed limit ranges
Speed -= speedDecrement;
}
}
}
You should declare myCar as a variable outside the GetCarData() method. Otherwise only the method GetCarData can access it. You can even think to make the variable static:
Like that:
public partial class Form1 : Form
{
// declare myCar for the entire class
private static CarClass myCar;
public Form1()
{
InitializeComponent();
}
private void GetCarData()
{
// init myCar
myCar = new CarClass();
...
}
}
Using AlarmManager application creates a notification in concrete time. We faced with a problem, from users' words notifications not appear or appear without any sound (settings are fine).
Please tell us what can it be connected with (users say that messengers applications create notifications without any problem)?
Can be the reason of it that we use NOT Notification.Builder and NotificationManager, but AppCompat alternatives: NotificationCompat.Builder and NotificationManagerCompat?
Here is my code:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Android.App;
using Android.Content;
using Android.OS;
using Android.Runtime;
using Android.Views;
using Android.Widget;
using Android.Support.V4.App;
using System.Threading;
using Android.Support.V4.Content;
using ME.Leolin.Shortcutbadger;
using Android.Media;
namespace WeeklyApp
{
[BroadcastReceiver]
public class WeeklyAlarmReceiver : WakefulBroadcastReceiver
{
private NotificationCompat.Builder builder;
private NotificationManagerCompat manager;
public static readonly int millisForPause = 1000;
private SettingsWorker settingsWorker;
private DealsDBWorker dealsDBWorker;
private int notificationValue;
private int soundValue;
private int badgeValue;
private DateTime currentDate;
private string currentStringDate;
private long currentTime;
private List<Task> currentDayTasks;
private Task notificationTask;
private DateTime startingUnixTime = new DateTime(1970, 1, 1);
private string defaultTitleText;
private string applicationName;
private string notificationText;
private string dealNotificationTime;
private int pendingIntentId = 0;
private int maxDealTextLength = 100;
private string dealNotificationText;
private DealsDBWorker dbWorker;
private DatesWorker datesWorker;
public static int notificationNumber = 0;
public static List<int> taskIDS;
private Intent mainIntent;
private static int currentAPIVersion = (int)Build.VERSION.SdkInt;
public WeeklyAlarmReceiver()
{
defaultTitleText = Application.Context.GetString(Resource.String.NotificationDefaultText);
applicationName = Application.Context.GetString(Resource.String.ApplicationName);
}
public override void OnReceive(Context context, Intent intent)
{
settingsWorker = new SettingsWorker();
dealsDBWorker = new DealsDBWorker();
mainIntent = new Intent(Application.Context, typeof(MainActivity));
mainIntent = Application.Context.PackageManager.GetLaunchIntentForPackage(Application.Context.PackageName);
mainIntent.SetFlags(ActivityFlags.BroughtToFront | ActivityFlags.ClearTop);
notificationValue = settingsWorker.GetNotificationsValue();
soundValue = settingsWorker.GetSoundValue();
badgeValue = settingsWorker.GetShowCounterValue();
if (builder == null)
{
builder = new NotificationCompat.Builder(context);
}
builder.SetContentTitle(applicationName);
manager = NotificationManagerCompat.From(Application.Context);
if (currentAPIVersion >= 21)
{
builder.SetSmallIcon(Resource.Drawable.ic_notification);
}
else
{
builder.SetSmallIcon(Resource.Drawable.ic_launcher);
}
GetCurrentNotificationTask();
if (taskIDS == null)
{
taskIDS = new List<int>();
}
if (notificationTask != null)
{
CreateNotification(context);
}
}
private void CreateNotification(Context context)
{
mainIntent.PutExtra("DealIdToShow", notificationTask.Id);
DateTime date = DateTime.Parse(notificationTask.TaskDate);
PendingIntent pendingIntent = PendingIntent.GetActivity(context, notificationTask.Id, mainIntent, PendingIntentFlags.UpdateCurrent);
builder.SetContentIntent(pendingIntent);
GetDealNotificationTime();
GetDealNotificationText();
notificationText = string.Format(defaultTitleText, dealNotificationTime, dealNotificationText);
builder.SetContentText(notificationText);
builder.SetStyle(new NotificationCompat.BigTextStyle().BigText(notificationText));
builder.SetAutoCancel(true);
SetNotification();
}
private void SetNotification()
{
if (soundValue != 0)
{
builder.SetVibrate(new long[] { 10, 1200 });
builder.SetSound(RingtoneManager.GetDefaultUri(RingtoneType.Notification));
}
if (notificationValue != 0)
{
notificationNumber++;
taskIDS.Add(notificationTask.Id);
if (Build.Manufacturer.Equals("Xiaomi", StringComparison.InvariantCultureIgnoreCase) && badgeValue != 0)
{
ShortcutBadger.RemoveCount(Application.Context);
manager.Cancel(101);
if(notificationNumber != 0)
{
//ShortcutBadger.ApplyNotification(Application.Context, resultNotification, notificationNumber);
ShortcutBadger.ApplyNotification(Application.Context, builder.Build(), notificationNumber);
}
else
{
ShortcutBadger.RemoveCount(Application.Context);
}
}
manager.Notify(101, builder.Build());
}
}
private void GetDealNotificationText()
{
int textLength = notificationTask.Text.Length;
if (textLength <= maxDealTextLength)
{
dealNotificationText = notificationTask.Text;
}
else
{
dealNotificationText = $"{notificationTask.Text.Substring(0, maxDealTextLength)}...";
}
}
private void GetDealNotificationTime()
{
DateTime resultTime = startingUnixTime.AddSeconds(notificationTask.TaskTime);
string defaultString = "{0}:{1}";
if (resultTime.Minute < 10)
{
defaultString = "{0}:0{1}";
}
dealNotificationTime = string.Format(defaultString, resultTime.Hour, resultTime.Minute);
}
private Task GetCurrentNotificationTask()
{
currentDate = new DateTime(DateTime.Now.Year, DateTime.Now.Month, DateTime.Now.Day, DateTime.Now.Hour, DateTime.Now.Minute, 0);
currentStringDate = currentDate.Date.ToString().Remove(10, 8);
currentDayTasks = dealsDBWorker.GetTasks(currentStringDate, true);
currentTime = (long)(currentDate - startingUnixTime).TotalSeconds;
if (currentDayTasks != null)
{
notificationTask = Array.Find(currentDayTasks.ToArray(), (a => a.TaskTime == currentTime));
if (notificationTask != null && (notificationTask.TaskTime % 10) != 0)
{
notificationTask = null;
}
}
else
{
notificationTask = null;
}
return notificationTask;
}
}
}
Background
I am writing a program, which collects different events (key press, mouse position, and others) and sends a single string to a serial port.
There is a small part of the program, where a key is pressed, to control movement (forward - W key; left - A key, Forward-left - WA key).
When an event happens, a method is invoked, which grabs a numeric string and processes in the FinalStringClass Class. On the main form , there is a method, which assigns collected value to a label.
However, I am encountering a problem with code due to lack of experience in programming :(
Main Form:
Serial port;
FinalStringClass fstr;
public Form1()
{
InitializeComponent();
//... Serial port settings
timer.Start();
fstr = new FinalStringClass(UpdateLabel2);
}
public void UpdateLabel2(string x, string y, string speed, string mvm) //
{
label2.Text = "x: " + x + "y: " + y + "speed: " + speed + "mvm: " + mvm;
}
private void timer_Tick(object sender, EventArgs e)
{
var up = KeyboardInfo.GetKeyState(Keys.W);
var down = KeyboardInfo.GetKeyState(Keys.S);
var left = KeyboardInfo.GetKeyState(Keys.A);
var right = KeyboardInfo.GetKeyState(Keys.D);
if (left.IsPressed)
{
if (up.IsPressed == true) // if W and A keys are pressed, ->
{
fstr.mvmMethod("7"); // this method is triggered
return;
}
if (down.IsPressed)
{
fstr.mvmMethod("9");
return;
}
if (right.IsPressed)
{
fstr.mvmMethod("1");
return;
}
fstr.mvmMethod("4"); //if W key is pressed, then this method is triggered
}
//... (other if condition statements)
label2.Text = fstr.FinalStringBuilder();
port.Write(fstr.FinalStringBuilder());
}
External Class:
class FinalStringClass
{
private Action<string, string, string, string> updateLabel2;
Action<String> _x, _y, _speed, _mvm;
string xF, yF, speedF, mvmF;
public FinalStringClass(Action<string, string, string, string> updateLabel2)
{
this.updateLabel2 = updateLabel2;
}
public FinalStringClass(Action<String> x, Action<String> y, Action<String> speed, Action<String> mvm)
{
_x = x;
_y = y;
_speed = speed;
_mvm = mvm;
}
public void xMethod(string x)
{
_x(x);
xF = x;
}
public void yMethod(string y)
{
_y(y);
yF = y;
}
public void speedMethod(string speed)
{
_speed(speed);
speedF = speed;
}
public void mvmMethod(string mvm)
{
_mvm(mvm);
mvmF = mvm;
}
public string FinalStringBuilder()
{
return xF + yF + speedF + mvmF;
}
}
When working with a single parameter, everything works fine. But dealing with multiple parameters causes a problem :(
Example of working with a single parameter (full working code):
Main Form
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO.Ports;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace FFApp
{
public partial class Form1 : Form
{
SerialPort port;
MyClass outside;
public Form1()
{
InitializeComponent();
timer.Start();
outside = new MyClass(UpdateLabel);
}
public void UpdateLabel(string str)
{
label1.Text = str;
}
private void init()
{
port = new SerialPort();
port.PortName = "COM1";
port.BaudRate = 115200;
try
{
port.Open();
}
catch (Exception e1)
{
MessageBox.Show(e1.Message);
}
}
public struct KeyStateInfo
{
private Keys key;
private bool isPressed;
private bool isToggled;
public KeyStateInfo(Keys key, bool ispressed, bool istoggled)
{
this.key = key;
isPressed = ispressed;
isToggled = istoggled;
}
public static KeyStateInfo Default
{
get
{
return new KeyStateInfo(Keys.None, false, false);
}
}
public Keys Key
{
get { return key; }
}
public bool IsPressed
{
get { return isPressed; }
}
public bool IsToggled
{
get { return isToggled; }
}
}
private void timer_Tick(object sender, EventArgs e)
{
var up = KeyboardInfo.GetKeyState(Keys.W);
var down = KeyboardInfo.GetKeyState(Keys.S);
var left = KeyboardInfo.GetKeyState(Keys.A);
var right = KeyboardInfo.GetKeyState(Keys.D);
Keyboard kb = new Keyboard();
if (left.IsPressed)
{
if (up.IsPressed == true)
{
outside.MyMethod("7");
return;
}
if (down.IsPressed)
{
outside.MyMethod("9");
return;
}
if (right.IsPressed)
{
outside.MyMethod("1");
return;
}
outside.MyMethod("4");
}
if (right.IsPressed)
{
if (up.IsPressed)
{
outside.MyMethod("6");
return;
}
if (down.IsPressed)
{
outside.MyMethod("8");
return;
}
if (left.IsPressed)
{
outside.MyMethod("1");
return;
}
outside.MyMethod("5");
}
if (up.IsPressed)
{
if (left.IsPressed)
{
outside.MyMethod("7");
return;
}
if (right.IsPressed)
{
outside.MyMethod("6");
return;
}
if (down.IsPressed)
{
outside.MyMethod("1");
return;
}
outside.MyMethod("2");
}
if (down.IsPressed)
{
if (left.IsPressed)
{
outside.MyMethod("9");
return;
}
if (right.IsPressed)
{
outside.MyMethod("8");
return;
}
if (up.IsPressed)
{
outside.MyMethod("9");
return;
}
outside.MyMethod("3");
}
if (!right.IsPressed && !left.IsPressed && !up.IsPressed && !down.IsPressed)
{
outside.MyMethod("1");
}
}
public class KeyboardInfo
{
[DllImport("user32")]
private static extern short GetKeyState(int vKey);
private KeyboardInfo()
{
}
public static KeyStateInfo GetKeyState(Keys key)
{
short keyState = GetKeyState((int)key);
int low = Low(keyState), high = High(keyState);
bool toggled = low == 1;
bool pressed = high == 1;
return new KeyStateInfo(key, pressed, toggled);
}
private static int High(int keyState)
{
return keyState > 0 ? keyState >> 0x10
: (keyState >> 0x10) & 0x1;
}
private static int Low(int keyState)
{
return keyState & 0xffff;
}
}
}
}
Class
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace FFApp
{
class MyClass
{
Action<String> labelSetter;
public MyClass(Action<String> labelSetter)
{
this.labelSetter = labelSetter;
}
public string MyProperty { get; set; }
public void MyMethod(string text)
{
labelSetter(text);
MyProperty = text;
}
}
}
Or is it possible within this code, to get changing values (store in a variable), when pressed W/A/D/S/W+A/W+D etc keys in order to allow building final string? ex: string finalstring = x + y + speed + pressed_key;
I have a windows application that sends and receives messages to/from a microprocessor using the serial port.
The application is working fine and does what is supposed to do. Now, I need to make some elaboration with the data I receive back from serial and I would like to access the variable "value" in SetText method.
How can I access the content of that variable from another method or class?
Thanks for helping.
delegate void SetTextCallback(string text);
private void SetText(string text)
{
if (this.txtOutput.InvokeRequired)
{
SetTextCallback d = new SetTextCallback(SetText);
this.BeginInvoke(d, new object[] { text });
}
else
{
txtOutput.AppendText(text);
}
// capture messages from serial port
if (txtOutput.Text.Length > 0)
{
MatchCollection mc = Regex.Matches(txtOutput.Text, #"(\+|-)?\d+");
if (mc.Count > 0)
{
long value = long.Parse(mc[mc.Count - 1].Value);
if (value > 1 && value < 1000)
{
textBox2.Text = value.ToString();
}
else if (value < 2000 && value > 1000)
{
value = value - 1000;
textBox3.Text = value.ToString();
}
}
}
}
private void serialPort1_DataReceived(object sender, System.IO.Ports.SerialDataReceivedEventArgs e)
{
try
{
SetText(serialPort1.ReadExisting());
}
catch (Exception ex)
{
SetText(ex.ToString());
}
}
Consider this :
Make a property
public long Value { get; set; }
Use this in your code.
if (txtOutput.Text.Length > 0)
{
MatchCollection mc = Regex.Matches(txtOutput.Text, #"(\+|-)?\d+");
if (mc.Count > 0)
{
value = long.Parse(mc[mc.Count - 1].Value);
if (value > 1 && value < 1000)
{
textBox2.Text = value.ToString();
}
else if (value < 2000 && value > 1000)
{
value = value - 1000;
textBox3.Text = value.ToString();
}
}
If you want to make sure that this property retains its value then use static one.
public static long Value { get; set; }
If the data is going to be used more than one place then don't hesitate just create a class with the list of output variables that are to be shared among the methods. Create properties for that variables within that class. Now create an object for this class globally and assign the retrieved values from the microprocessor to the properties within this globally declared object. You can access this in any place. Because of this is a windows application the data will retain until you clear or the application was closed.
Here is the code. I have a textbox and two buttons in the windows app. One button to get the data and another to show the data. The data was get from the user using the textbox. After getting the data once on clicking the show data button it will show the data pushed to the object as many times you want.
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace WindowsFormsApplication1
{
public partial class Form1 : Form
{
// Declare Global Variable
DataHolder objDataHolder = new DataHolder();
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
// Here use your code to load the data retrieved from Microprocessor
objDataHolder.UserData = txtUserData.Text;
}
private void button2_Click(object sender, EventArgs e)
{
MessageBox.Show(objDataHolder.UserData);
}
}
// Class to hold Data
public class DataHolder
{
// Here have a list variables that you need to maintain that are retrieved from Microrocessor.
private string _userdata = string.Empty;
// Here have a list Properties that you need to maintain that are retrieved from Microrocessor.
public string UserData
{
get
{
return _userdata;
}
set
{
_userdata = value;
}
}
}
}
You can access the variable in other class using "Static" variable or instance variable
public class Demo1
{
//Static variable can be accessed without instantiating an instance of Demo1
public static int Number; //Demo1.Number
public string Info {get;set;}
}
public class AnotherClass
{
void DoSth()
{
Demo1.Number ++;
}
}
or if you have an instance of Demo1, say demo1Instance
demo1Instance.Info="Sth you like";
This is what I have done and it is now working.Thanks to all of you for the good suggestions. I am quite sure that I am going to use your examples very soon in the additional developments of the application.
internal long value;
private void SetText(string text)
{
if (this.txtOutput.InvokeRequired)
{
SetTextCallback d = new SetTextCallback(SetText);
this.BeginInvoke(d, new object[] { text });
}
else
{
txtOutput.AppendText(text);
}
// capture messages from serial port
if (txtOutput.Text.Length > 0)
{
MatchCollection mc = Regex.Matches(txtOutput.Text, #"(\+|-)?\d+");
if (mc.Count > 0)
{
value = long.Parse(mc[mc.Count - 1].Value);
if (value > 1 && value < 1000)
{
textBox2.Text = value.ToString();
}
else if (value < 2000 && value > 1000)
{
value = value - 1000;
textBox3.Text = value.ToString();
}
}
}
}
I am trying to check for the word "Alarm" in my isolated storage before saving.
If the word "Alarm" is exist i will change the "Alarm" to "Alarm1" then if "Alarm1" is exist will change to "Alarm2".
How should i go about doing it?
Below is my code but it is not working:
if (labelTextBox.Text == "")
{
try
{
using (IsolatedStorageFile storage = IsolatedStorageFile.GetUserStoreForApplication())
{
foreach (string label in storage.GetFileNames("*"))
{
MessageBox.Show(label);
}
}
}
catch (Exception)
{
}
int i = 0;
i++;
labelTextBox.Text = "Alarm" + i;
alarmLabel = (labelTextBox.Text.ToString()).Replace(" ", "_");
}
You could use the IsolatedStorageSettings.ApplicationSettings, which is more appropriated for object (e.r. string) handling.
I made a small sample which makes use of this class:
using System;
using System.IO.IsolatedStorage;
using System.Windows;
using Microsoft.Phone.Controls;
namespace SidekickWP7
{
public partial class Page1 : PhoneApplicationPage
{
const string MYALARM = "MyAlarm";
public Page1()
{
InitializeComponent();
Loaded += new RoutedEventHandler(Page1_Loaded);
}
void Page1_Loaded(object sender, RoutedEventArgs e)
{
int intAlarm = 0;
Int32.TryParse(Load(MYALARM).ToString(), out intAlarm);
intAlarm++;
MessageBox.Show(intAlarm.ToString());
Save(MYALARM, intAlarm);
}
private static object Load(string strKey)
{
object objValue;
if (IsolatedStorageSettings.ApplicationSettings.TryGetValue<object>(strKey, out objValue) == false)
{
objValue = String.Empty;
}
return objValue;
}
private static void Save(string strKey, object objValue)
{
IsolatedStorageSettings.ApplicationSettings[strKey] = objValue;
IsolatedStorageSettings.ApplicationSettings.Save();
}
}
}
try this:
using (var store = IsolatedStorageFile.GetUserStoreForApplication())
{
int highestNumberFound = -1;
foreach (var fileName in store.GetFileNames())
{
if (fileName.StartsWith("alarm"))
{
if (fileName == "alarm")
{
if (highestNumberFound < 0)
{
highestNumberFound = 0;
}
}
else if (fileName.Length > 5)
{
int numb;
if (int.TryParse(fileName.Substring(5), out numb))
{
if (numb > highestNumberFound)
{
highestNumberFound = numb;
}
}
}
}
}
string toCreate = "alarm";
if (++highestNumberFound > 0)
{
toCreate += highestNumberFound.ToString();
}
store.CreateFile(toCreate);
}
Not pretty but it should work.
I storngly suspect that creating empty files with different names isn't the best way to achieve whatever it is that you're trying to do though.