This question already has answers here:
C# - Read in a large (150MB) text file into a Rich Text Box
(2 answers)
Closed 1 year ago.
I have a large text files for example 39000 lines and above , i want to load it into richtextbox , using normal way like this:
Richtextbox1.Text=File.ReadAllLines(file);
or
Richtextbox1.LoadFile(...);
it take long time and freeze the UI even i use BackgroundWorker, so i decide to split file into parts each part is 1000 lines and append them to the richtextbox , i mean i read 1000 lines from file into string and then append it to the richtextbox, here is my code:
private void Worker_DoWork(object sender, DoWorkEventArgs e)
{
StreamReader reader = null;
try
{
//
int ProgressPercentage = 0;
//enable stop Correct button
BTN_Send_Ref.Invoke((MethodInvoker)(() =>
{
BTN_Send_Ref.Enabled = true;
}));
string[] Lines = File.ReadAllLines(InputTextFile);
//MessageBox.Show("Lines : " + Lines.Length);
int i= 0;
int j = 0;
string LinesCollection = "";
while (true)
{
if (worker.CancellationPending)
{
if (reader != null)
{
reader.Close();
reader = null;
}
e.Cancel = true;
//cancel backgroundworker
return;
}
LinesCollection = "";
if (i > Lines.Length ||
j >= Lines.Length)
{
break;
}
i += 1000;
if (i >= Lines.Length)
{
i = Lines.Length ;
}
while ( j < i)
{
if (worker.CancellationPending)
{
if (reader != null)
{
reader.Close();
reader = null;
}
e.Cancel = true;
//cancel backgroundworker
return;
}
if (j < Lines.Length)
{
if (LinesCollection == "")
{
LinesCollection = Lines[j];
}
else
{
LinesCollection += Environment.NewLine + Lines[j];
}
}
ProgressPercentage = (int)Math.Round((((double)j) / Lines.Length) * 100);
if (ProgressPercentage < 100)
{
//report progress
worker.ReportProgress(ProgressPercentage);
}
ProgressPercentage++;
j++;
}
RichTXT_OutText_Ref.Invoke((MethodInvoker)(() =>
{
RichTXT_OutText_Ref.AppendText(LinesCollection +Environment.NewLine);
}));
LBL_CountOfChars_Ref.Invoke((MethodInvoker)(() =>
{
LBL_CountOfChars_Ref.Text = "(" + RichTXT_OutText_Ref.Text.Length + ") Char";
LBL_CountOfChars_Ref.Update();
}));
LBL_CountOfLines_Ref.Invoke((MethodInvoker)(() =>
{
LBL_CountOfLines_Ref.Text = "(" + RichTXT_OutText_Ref.Lines.Length + ") Line";
LBL_CountOfLines_Ref.Update();
}));
}
/*int Tmp_Count = 0;
if (RichTXT_OutText_Ref.InvokeRequired)
{
RichTXT_OutText_Ref.Invoke((MethodInvoker)(() =>
{
RichTXT_OutText_Ref.LoadFile(InputTextFile, RichTextBoxStreamType.PlainText);
}));
}
else
{
RichTXT_OutText_Ref.LoadFile(InputTextFile, RichTextBoxStreamType.PlainText);
}
LBL_CountOfChars_Ref.Invoke((MethodInvoker)(() =>
{
LBL_CountOfChars_Ref.Text = "(" + RichTXT_OutText_Ref.Text.Length + ") Char";
LBL_CountOfChars_Ref.Update();
}));
LBL_CountOfLines_Ref.Invoke((MethodInvoker)(() =>
{
LBL_CountOfLines_Ref.Text = "(" + RichTXT_OutText_Ref.Lines.Length + ") Line";
LBL_CountOfLines_Ref.Update();
}));
*/
/*reader= File.OpenText(InputTextFile);
string Line = "";
int LinesCounter = 0;
while ((Line = reader.ReadLine()) != null)
{
if (worker.CancellationPending)
{
if (reader != null)
{
reader.Close();
reader = null;
}
e.Cancel = true;
//cancel backgroundworker
return;
}
if(LinesCounter >0 && LinesCounter <= 1000)
{
RichTXT_OutText_Ref.Invoke((MethodInvoker)(() =>
{
RichTXT_OutText_Ref.AppendText(LinesCollection);
}));
LinesCollection = "";
LinesCounter = 0;
}
else
{
if (LinesCollection == "")
{
LinesCollection= Line;
}
else
{
LinesCollection += Environment.NewLine + Line;
}
}
LBL_CountOfChars_Ref.Invoke((MethodInvoker)(() =>
{
LBL_CountOfChars_Ref.Text = "(" + RichTXT_OutText_Ref.Text.Length + ") Char";
LBL_CountOfChars_Ref.Update();
}));
LBL_CountOfLines_Ref.Invoke((MethodInvoker)(() =>
{
LBL_CountOfLines_Ref.Text = "(" + RichTXT_OutText_Ref.Lines.Length + ") Line";
LBL_CountOfLines_Ref.Update();
}));
//calculate progress value
ProgressPercentage = (int)Math.Round((((double)PercentageCounter) / Lines.Length) * 100);
if (ProgressPercentage < 100)
{
//report progress
worker.ReportProgress(ProgressPercentage);
}
TempCount++;
PercentageCounter++;
Tmp_Count++;
}
*/
if (reader != null)
{
reader.Close();
reader = null;
}
//disable Correct button because
//we are out of loop
if (BTN_Send_Ref != null)
{
//we call this btn Correct
//from another thread
//so we must use Invoke
BTN_Send_Ref.Invoke((MethodInvoker)(() =>
{
BTN_Send_Ref.Enabled = false;
}));
}
}
catch (Exception ex)
{
if (reader != null)
{
reader.Close();
reader = null;
}
MessageBox.Show(ex.Message+"\n"+ex.StackTrace.ToString());
throw ex;
}
}
the problem is that the code work fine with some file say less than 1000 but when i use large file has size greater than 1000,the count of lines is less than actual file lines
for example i attach text file
my text file
which has size 62077 but the after use my code the richtextbox lines is 62028, and count of characters also is less the actual count of characters of file, but the start and the end of content in richtextbox and file are the same, i do not know where is the error, all i want is to read text file , combine every 1000 lines in one string append it the richtextbox repeat the operation until end of file content.
i do not want to use Richtextbox1.LoadFile(...)and Richtextbox1.Text=File.ReadAllLines(file); because they freeze and hung the UI this happen when using large files more than 39000 lines,
i want to know what is the wrong with code?why dose not get right result?
i hope you help me.
i use this code and it work fine:
private void Worker_DoWork(object sender, DoWorkEventArgs e)
{
try
{
//
int ProgressPercentage = 0;
BTN_Send_Ref.Invoke((MethodInvoker)(() =>
{
BTN_Send_Ref.Enabled = true;
}));
string[] Lines = File.ReadAllLines(InputTextFile);
string LinesCollection = "";
for(int x = 0; x < Lines.Length; x++)
{
if (worker.CancellationPending)
{
e.Cancel = true;
//cancel backgroundworker
return;
}
LinesCollection += Lines[x] + Environment.NewLine;
if (x>0 && x % 1000 == 0)
{
RichTXT_OutText_Ref.Invoke((MethodInvoker)(() =>
{
RichTXT_OutText_Ref.AppendText(LinesCollection );
}));
LinesCollection = "";
LBL_CountOfChars_Ref.Invoke((MethodInvoker)(() =>
{
LBL_CountOfChars_Ref.Text = "(" + RichTXT_OutText_Ref.Text.Length + ") Char";
LBL_CountOfChars_Ref.Update();
}));
LBL_CountOfLines_Ref.Invoke((MethodInvoker)(() =>
{
LBL_CountOfLines_Ref.Text = "(" + RichTXT_OutText_Ref.Lines.Length + ") Line";
LBL_CountOfLines_Ref.Update();
}));
}
if(x==Lines.Length-1 && LinesCollection != "")
{
RichTXT_OutText_Ref.Invoke((MethodInvoker)(() =>
{
RichTXT_OutText_Ref.AppendText(LinesCollection.TrimEnd(Environment.NewLine.ToCharArray()) );
}));
LinesCollection = "";
LBL_CountOfChars_Ref.Invoke((MethodInvoker)(() =>
{
LBL_CountOfChars_Ref.Text = "(" + RichTXT_OutText_Ref.Text.Length + ") Char";
LBL_CountOfChars_Ref.Update();
}));
LBL_CountOfLines_Ref.Invoke((MethodInvoker)(() =>
{
LBL_CountOfLines_Ref.Text = "(" + RichTXT_OutText_Ref.Lines.Length + ") Line";
LBL_CountOfLines_Ref.Update();
}));
}
ProgressPercentage = (int)Math.Round((((double)x) / Lines.Length) * 100);
if (ProgressPercentage < 100)
{
//report progress
worker.ReportProgress(ProgressPercentage);
}
}
//disable Correct button because
//we are out of loop
if (BTN_Send_Ref != null)
{
BTN_Send_Ref.Invoke((MethodInvoker)(() =>
{
BTN_Send_Ref.Enabled = false;
}));
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message+"\n"+ex.StackTrace.ToString());
throw ex;
}
}
Related
When someone puts arabic numbers in my entry , it ends the app .
I'm trying to restrict entry to show only English number or convert arabic number to english
I'm trying it on real device and not working at all unfortunately .
Dictionary<string, string> numberNames;
// SUM1 لتخزين النتيجة الاولة
int SUM1 = 0;
// SUM2 لتخزين النتيجة الثانية
int SUM2 = 0;
// DisplayPromptAsync تخزين حالة الاشعار
string action;
// لتبديل بين entrys
int tap = 1;
// عدد الاعبين
int playercount = 1;
int count = 0;
bool scroll = false;
public Blootrecord(bool newplay)
{
InitializeComponent();
if (newplay)
{
DisplayPrompt(lblname1, "اسم فريقهم");
DisplayPrompt(lblname2, "اسم فريقنا?");
}
else
{
// اذا مالنت الثيمة ب False هذا يعني انه يريد الرجوع لاخر لعية
// هذه اسطر لجلب اخر قيم تم تخزينها
lblname1.Text = Preferences.Get("lblname1", "");
lblname2.Text = Preferences.Get("lblname2", "");
num1.Text = Preferences.Get("num1", "");
num2.Text = Preferences.Get("num2", "");
SUM1 = Convert.ToInt32(Preferences.Get("SUM1", "0"));
SUM2 = Convert.ToInt32(Preferences.Get("SUM2", "0"));
count = Convert.ToInt32(Preferences.Get("count", "0"));
}
numberNames = new Dictionary<string, string>();
numberNames.Add("0", "۰"); //adding a key/value using the Add() method
numberNames.Add("1", "۱");
numberNames.Add("2", "۲");
numberNames.Add("3", "۳");
numberNames.Add("4", "٤");
numberNames.Add("5", "٥");
numberNames.Add("6", "٦");
numberNames.Add("7", "٧");
numberNames.Add("8", "۸");
numberNames.Add("9", "۹");
scrollView.HeightRequest = num1.HeightRequest;
}
/// <summary>
/// هذه دالة لعررض الاشعار
/// </summary>
/// <param name="label"></param>
/// /// <param name="label2"></param>
/// <param name="str"></param>
async void DisplayPrompt(Label label, string str)
{
var s = await DisplayPromptAsync("Alert", str);
if (string.IsNullOrEmpty(s))
label.Text = "فريق" + playercount++;
else
label.Text = s;
}
/// <summary>
/// زر سجل
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
///
private async void btnRegister_Clicked(object sender, EventArgs e)
{
try
{
Entnum1 = ARCH(Entnum1);
Entnum2 = ARCH(Entnum2);
scrollView.HeightRequest = num1.HeightRequest;
scroll = false;
// اضافة سط في Editors مع القيمه المدخله
num1.Text += "\n" + Entnum1.Text;
num2.Text += "\n" + Entnum2.Text;
//اذا كان الentry فارغ يبدل القيمه ب صفر
if (string.IsNullOrEmpty(Entnum1.Text))
{
num1.Text += "0";
}
if (string.IsNullOrEmpty(Entnum2.Text))
{
num2.Text += "0";
}
//تحويل القيمه الي عدد صحيح وجمعها ع اخر قميه
SUM1 += int.Parse(num1.Text.Substring(num1.Text.LastIndexOf("\n") + 1));
SUM2 += int.Parse(num2.Text.Substring(num2.Text.LastIndexOf("\n") + 1));
// اذا كانت القيمه اقل من 152 يتم اضافة سطر ثم خط ثم قيمه الجمع في كل Editor
if (SUM1 < 152 && SUM2 < 152)
{
num1.Text += "\n" + "------";
num2.Text += "\n" + "------";
num1.Text += "\n" + SUM1;
num2.Text += "\n" + SUM2;
}
else
{
// يتم عرض اكير قيمه مع اكبر فائز
if (SUM1 > SUM2)
{
action = await DisplayActionSheet(" هاردلك الفوز لهم " + SUM1 + " ", "اغلاق", "لعبة جديدة");
}
else if (SUM1 < SUM2)
{
action = await DisplayActionSheet(" مبروك الفوز لنا" + SUM2 + "", "اغلاق", "لعبة جديدة");
}
else
{
action = await DisplayActionSheet("تعادل", "اغلاق", "لعبة جديدة");
}
// اذا قمت بأختيار لعبة جديدة
if (action == "لعبة جديدة")
{
// يحذف جميع القيم ولاكن يبقي اسم العبين
num1.Text = num2.Text = "0";
Entnum1.Text = Entnum2.Text = null;
SUM1 = SUM2 = 0;
await scrollView.ScrollToAsync(num1, ScrollToPosition.Start, true);
count = 0;
scroll = true;
}
}
Entnum1.Text = Entnum2.Text = null;
// store data
// تخزين البيانات في كل مره
Preferences.Set("lblname1", lblname1.Text);
Preferences.Set("lblname2", lblname2.Text);
Preferences.Set("num1", num1.Text);
Preferences.Set("num2", num2.Text);
Preferences.Set("SUM1", SUM1.ToString());
Preferences.Set("SUM2", SUM2.ToString());
count++;
if (count >= 5 && count <= 7 && !scroll)
{
await scrollView.ScrollToAsync(num1, ScrollToPosition.Center, true);
}
else if (count > 7 && !scroll)
{
await scrollView.ScrollToAsync(num1, ScrollToPosition.End, true);
}
}
catch (Exception ex)
{
// في حالة وجود خطأ غير متوقع
await DisplayAlert("Opps!", ex.Message, "Ok");
await Navigation.PopAsync();
}
}
void btnBack_Clicked(System.Object sender, System.EventArgs e)
{
try
{
if (num1.Text != "0" && num2.Text != "0")
{
// يتم اذالة ثلاث اسطر وطرح قيمة السطر الثالث من المجموع الكلي ثم ازالة السطر الثالث
// editor number one
num1.Text = num1.Text.Remove(num1.Text.LastIndexOf("\n"));
num1.Text = num1.Text.Remove(num1.Text.LastIndexOf("\n"));
SUM1 -= int.Parse(num1.Text.Substring(num1.Text.LastIndexOf("\n") + 1));
num1.Text = num1.Text.Remove(num1.Text.LastIndexOf("\n"));
// editor number two
num2.Text = num2.Text.Remove(num2.Text.LastIndexOf("\n"));
num2.Text = num2.Text.Remove(num2.Text.LastIndexOf("\n"));
SUM2 -= int.Parse(num2.Text.Substring(num2.Text.LastIndexOf("\n") + 1));
num2.Text = num2.Text.Remove(num2.Text.LastIndexOf("\n"));
}
}
catch (Exception ex)
{
DisplayAlert("Opps!", ex.Message, "Ok");
}
}
private void Entnum1_Focused(object sender, FocusEventArgs e)
{
tap = 1;
}
private void Entnum2_Focused(object sender, FocusEventArgs e)
{
tap = 2;
}
private void Entnum2_PropertyChanged(object sender, System.ComponentModel.PropertyChangedEventArgs e)
{
// في حالة اختيار Closr
if (action == "اغلاق")
{
// حزف جميع القيم المخزنه
Preferences.Clear();
// الرجوع الي الصفحة الاولة
Navigation.PopAsync();
}
}
Entry ARCH(Entry entry)
{
for (var i = 0; i < 10; i++)
{
entry.Text = entry.Text.Replace(numberNames[i.ToString()], i.ToString());
}
return entry;
}
}
}
You could try this method to convert it:
private string convertArabic(string arabicNum)
{
var chArr = arabicNum.ToCharArray();
var sb = new Java.Lang.StringBuilder();
foreach (var ch in chArr)
{
if (Character.IsDigit(ch))
{
sb.Append(Character.GetNumericValue(ch));
}
else if (ch == '٫')
{
sb.Append(".");
}
else
{
sb.Append(ch);
}
}
return sb.ToString();
}
I have dynamically created array CheckBoxes and I want to do a proper validation if none of them are selected inside the Panel but if I keep on using for loops, the MessageBox keeps on appearing.
Can anyone help me find a way to do this better? I just want to check if a checkbox control is checked inside the Panel and if not, display a messagebox that will say "Select a Checkbox!" only ONCE.
Here is the code that I made for the dynamically created checkboxes in a panel:
for (int z = 0; z <= dataGridView.Columns.Count - 1; z++)
{
chk[z] = new CheckBox();
chk[z].Name = dataGridView.Columns[z].Name;
chk[z].Text = dataGridView.Columns[z].Name;
chk[z].AutoCheck = true;
chk[z].Bounds = new Rectangle(10, 20 + padding + dynamicHeight, 40, 22);
chk[z].Location = new Point(0, dynamicHeight);
chk[z].Size = new Size(120, 21);
panelCol.BackColor = Color.White;
//MessageBox.Show(chk[z].Name + "" + dataGridView.Columns[z].Name);
panelCol.Controls.Add(chk[z]);
//panelCol.AutoScrollMinSize = new Size(0, 100);
dynamicHeight += 20;
panelCol.Size = new Size(120, dynamicHeight);
}
Here is the code that I have came up:
btnValidate.MouseClick += (s, e) => //btnValidate Event
{
for (int z = 0; z < dataGridView.Columns.Count - 1; z++ )
{
if(chk[z].Checked == true)
{
ValidateCheck(dataGridView, chk);
}
else if(chk[z].Checked == false)
{
MessageBox.Show("Select a CheckBox!");
}
}
};
ValidateCheck method:
public static void ValidateCheck(DataGridView dataGridView, CheckBox[] chk)
{
FileStream fs = new FileStream(#"C:\brandon\InvalidColumnCheck.txt", FileMode.OpenOrCreate, FileAccess.Write);
StreamWriter sw = new StreamWriter(fs);
sw.BaseStream.Seek(0, SeekOrigin.End);
StringBuilder sb = new StringBuilder();
decimal num;
sw.WriteLine("----------------------------");
sw.WriteLine("");
for (int j = 0; j < dataGridView.ColumnCount - 1; j++)
{
if (chk[j].Checked == true && chk[j].Name.Contains(dataGridView.Columns[j].Name))
{
string column = chk[j].Name;
for (int k = 0; k < dataGridView.RowCount; k++)
{
if (!Decimal.TryParse(dataGridView.Rows[k].Cells[column].Value.ToString(), out num))
{
if (dataGridView.Rows[k].Cells[dataGridView.Columns[column].Name].Value.ToString() == null || dataGridView.Rows[k].Cells[dataGridView.Columns[column].Name].Value.ToString() == "" || dataGridView.Rows[k].Cells[dataGridView.Columns[column].Name].Value.ToString() == column)
{
}
else
{
//MessageBox.Show("COLUMN" + dataGridView.Columns[j].Name.ToString() + "" + dataGridView.Rows[k].Cells[column].Value.ToString() + " NOT A DECIMAL!");
sb.AppendLine("[Column " + chk[j].Name.ToString().ToUpper() + "] :" + dataGridView.Rows[k].Cells[column].Value.ToString() + " NOT A DECIMAL!");
}
}
}
sb.AppendLine("");
}
}
if (sb.ToString() == null || sb.ToString() == "" || sb.Length < dataGridView.Columns.Count)
{
sw.WriteLine("No Errors!");
sw.WriteLine("");
sw.WriteLine("----------------------------");
MessageBox.Show("No errors!");
Process.Start(#"C:\brandon\InvalidColumnCheck.txt");
}
else if (sb.ToString() != null || sb.ToString() != "")
{
sw.WriteLine(sb.ToString());
sw.WriteLine("----------------------------");
//MessageBox.Show(sb.ToString());
Process.Start(#"C:\brandon\InvalidColumnCheck.txt");
}
sw.Flush();
sw.Close();
}
Here another way to get all Checkboxes from Panel, which are checked (with Linq):
List<CheckBox> selectedItems = panelCol.Controls.OfType<CheckBox>().Where(chk => chk.Checked).ToList();
Please change the validation method like below,
public List<CheckBox> GetSelectedItems()
{
List<CheckBox> selectedList = new List<CheckBox>();
foreach(Control control in panelCol.Controls) // panelCol is your panel
{
if(control is CheckBox)
{
CheckBox chkCtrl = control as CheckBox;
if(chkCtrl.Checked)
{
selectedList.Add(chkCtrl);
}
}
}
return selectedList;
}
btnValidate.MouseClick += (s, e) =>//btnValidate Event
{
List<CheckBox> selectedItems = GetSelectedItems();
if(selectedItems.Count == 0)
MessageBox.Show("Select a CheckBox!");
else{
// Continue with other validation for the selected checkboxes from the list
}
}
Hope it helps!
I have a .NET Winforms-based program I wrote in C# where I programmatically select text within a TextBox using the Select() method. I can see the selected text on the screen and the SelectionLength member reports an accurate amount of selected characters, but the SelectedText member doesn't contain any text:
int indexPeriod = strLectureText.IndexOfAny(terminators, indexStart);
thisTextbox.Focus();
if (indexPeriod > -1)
{
thisTextbox.Select(indexStart, (indexPeriod - indexStart) + 1);
}
else
{
thisTextbox.Select(indexStart, thisTextbox.Text.Length);
}
Log.Debug("jtext len=" + thisTextbox.SelectionLength + " txt=" + thisTextbox.SelectedText);
thisTextbox.ScrollToCaret();
What's going on?
Update Nov 16 2013
I am adding additional code per #KingKing's request:
delegate void delegateMoveToNextTextFragment(ref TextBox thisTextbox, char[] terminators);
private void MoveToNextTextFragment(ref TextBox thisTextbox, char[] terminators)
{
string strLectureText = String.Empty;
strLectureText = thisTextbox.Text;
int currentStartPos = thisTextbox.SelectionStart + thisTextbox.SelectionLength - 1
// search the rest of the buffer after the currently-selected string to find the next period
int skipLastChar = 0;
// don't include last selected character in search
try
{
if ((thisTextbox.SelectionLength > 0) & (strLectureText[currentStartPos] != '.'))
{
skipLastChar = 1;
}
}
catch (Exception ex)
{
Debug.WriteLine("exception caught! ex=" + ex.Message);
skipLastChar = 0;
}
int indexStart = 0;
if (currentStartPos == 0)
{
indexStart = 0;
}
else
{
indexStart = currentStartPos + 1;
}
int indexPeriod = strLectureText.IndexOfAny(terminators, indexStart);
if (indexPeriod > -1)
{
thisTextbox.Select(indexStart, (indexPeriod - indexStart) + 1);
}
else
{
thisTextbox.Select(indexStart, thisTextbox.Text.Length);
}
thisTextbox.Focus();
Log.Debug("jtext len=" + thisTextbox.SelectionLength + " txt=" + thisTextbox.SelectedText);
thisTextbox.ScrollToCaret();
}
How to display multiple icons on same points in googlemap in .net using goolemap api 3
Below is my code
public void selectTrainings(string strQuery)
{
try
{
clsTblMembers objtblMember = new clsTblMembers();
objtblMember.StrEmail = strQuery.ToString();
DataTable dt = objtblMember.SelectSearch();
if (dt != null)
{
int i;
for (i = 0; i < dt.Rows.Count; i++)
{
if (dt.Rows[i]["Latitude"].ToString() != "" && dt.Rows[i]["Longitude"].ToString() != "")
{
string StrLat = dt.Rows[i]["Latitude"].ToString();
string StrLon = dt.Rows[i]["Longitude"].ToString();
double Numlat;
bool isNumlat = double.TryParse(StrLat, out Numlat);
double Numlon;
bool isNumlon = double.TryParse(StrLon, out Numlon);
if ((isNumlat) && (isNumlon))
{
//coordinates datatype =double;
m1 = new MapControl.MapMarker();
m1.Latitude = Convert.ToDouble(dt.Rows[i]["Latitude"].ToString());
m1.Longitude = Convert.ToDouble(dt.Rows[i]["Longitude"].ToString());
getTraining(Convert.ToInt32(dt.Rows[i]["intId"].ToString()), Convert.ToInt32(dt.Rows[i]["intTypeId"].ToString()), dt.Rows[i]["strCode"].ToString(), dt.Rows[i]["strConductedBy"].ToString(), dt.Rows[i]["dtFromDate"].ToString(), dt.Rows[i]["dtToDate"].ToString(), dt.Rows[i]["strName"].ToString(), dt.Rows[i]["strUC"].ToString(), dt.Rows[i]["strVillage"].ToString());
if (dt.Rows[i]["intTypeId"].ToString() == "1")
{
m1.Title ="CMST - "+ dt.Rows[i]["strCode"].ToString();
m1.Image = "mapIcons/t1.png";
}
else if (dt.Rows[i]["intTypeId"].ToString() == "2")
{
m1.Title = "LMST - " + dt.Rows[i]["strCode"].ToString();
m1.Image = "mapIcons/t2.png";
}
else if (dt.Rows[i]["intTypeId"].ToString() == "3")
{
m1.Title = " Govt.Official Training - " + dt.Rows[i]["strCode"].ToString();
m1.Image = "mapIcons/t3.png";
}
else if (dt.Rows[i]["intTypeId"].ToString() == "4")
{
m1.Title = "Gender Based Violence - " + dt.Rows[i]["strCode"].ToString();
m1.Image = "mapIcons/pg.png";
}
else if (dt.Rows[i]["intTypeId"].ToString() == "5")
{
m1.Title = "Human Rights - " + dt.Rows[i]["strCode"].ToString();
m1.Image = "mapIcons/ph.png";
}
else
{
m1.Title = "Livelihoods Skills Training - " + dt.Rows[i]["strCode"].ToString();
m1.Image = "mapIcons/t4.png";
}
m1.ImageSize1 = 32.0;
m1.ImageSize2 = 37.0;
m1.ImagePoint1 = 0;
m1.ImagePoint2 = 0;
m1.ImagePoint3 = 16.0;
m1.ImagePoint4 = 18.0;
m1.Shadow = "mapIcons/shadow.png";
m1.ShadowSize1 = 51.0;
m1.ShadowSize2 = 37.0;
m1.ShadowPoint1 = 0;
m1.ShadowPoint2 = 0;
m1.ShadowPoint3 = 16.0;
m1.ShadowPoint4 = 18.0;
GoogleMap.Markers.Add(m1);
}
}
}
}
}
catch (Exception ex)
{
}
}
I am working on a Reverse polish notation calculator. I created a method that will take care of the calculations but there are three lines in my code that are causing an error. After every = an operation is performed and then displayed. I am trying to grab the string from TxtInputBox and convert to integers but it always shows the catch message Please check the input. Then nothing gets calculated or display. I am sure that my first if statement will check for actual integers and avoid the characters. My ultimate goal is to input a formula in rpn format and have the result display in the multiline textbox.
Sample Input 5 6 -=
Code
namespace rpncalc
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void RPNCalc(TextBox TxtBoxInputbox, TextBox TxtBoxOutputbox)
{
Stack<int> stackone = new Stack<int>();
stackone.Clear();
string[] inputarray = TxtBoxInputbox.Text.Split();
int end = inputarray.Length - 1;
int numinput;
int i = 0;
do
{
if(inputarray[i] != "=" && inputarray[i] != "+" && inputarray[i] != "-" && inputarray[i] != "*" && inputarray[i] != "/")
{
try
{
numinput = Convert.ToInt32(inputarray[i]);
stackone.Push(numinput);
}
catch
{
MessageBox.Show("Please check the input");
}
}
else if (inputarray[i]== "+")
{
try
{
int store1 = stackone.Pop();
int store2 = stackone.Pop();
stackone.Push(store2 + store1);
}
catch
{
}
}
else if (inputarray[i]== "-")
{
try
{
int store1 = stackone.Pop();
int store2 = stackone.Pop();
stackone.Push(store2 + store1);
}
catch
{
}
}
else if (inputarray[i]== "+")
{
try
{
int store1 = stackone.Pop();
int store2 = stackone.Pop();
stackone.Push(store2 + store1);
}
catch
{
}
}
else if (inputarray[i]== "*")
{
try
{
int store1 = stackone.Pop();
int store2 = stackone.Pop();
stackone.Push(store2 + store1);
}
catch
{
}
}
else if (inputarray[i]== "/")
{
try
{
int store1 = stackone.Pop();
int store2 = stackone.Pop();
stackone.Push(store2 + store1);
}
catch
{
}
}
}
while(i < end && inputarray[i]!= "=" && stackone.Count != 0);
string txtout = TxtInputBox + " " + stackone.Pop().ToString() + Environment.NewLine;
TxtOutputBox.AppendText(txtout);
TxtInputBox.Clear();
}
private void Btn_Calc_Click(object sender, EventArgs e)
{
RPNCalc(TxtInputBox, TxtOutputBox);
}
}
}
The Split command, with no argument, is splitting the string on spaces and other whitespace.
There is no space in the input between -= so it is treated as one token that doesn't match the tests in the if statement.
Original answer incorrectly suggested that Split with no argument was splitting into individual characters.
What are you doing to increment i after each iteration of your do loop? I tried out your code and it seems like i is never incremented. Also, when you catch and run
catch
{
MessageBox.Show("Please check the input");
}
You could perhaps change it to:
catch (Exception e)
{
MessageBox.Show(e.ToString());
}
so you could be sure of just what you're catching, and why.
Edit:
Here's my version of your code, now working correctly:
i is incremented in each iteration
Fixed the typo in the minus, multiplication and division operators that made them do addition instead
Removed the redundant addition operator
namespace rpncalc {
public partial class Form1 : Form {
public Form1 () {
InitializeComponent();
}
private void RPNCalc (TextBox TxtBoxInputbox, TextBox TxtBoxOutputbox) {
Stack<int> stackone = new Stack<int>();
stackone.Clear();
string[] inputarray = TxtBoxInputbox.Text.Split();
int end = inputarray.Length - 1;
int numinput;
int i = 0;
do {
if (inputarray[i] != "=" && inputarray[i] != "+" && inputarray[i] != "-" && inputarray[i] != "*" && inputarray[i] != "/") {
try {
numinput = Convert.ToInt32(inputarray[i]);
stackone.Push(numinput);
} catch (Exception e) {
MessageBox.Show(e.ToString());
}
} else if (inputarray[i] == "+") {
try {
int store1 = stackone.Pop();
int store2 = stackone.Pop();
stackone.Push(store2 + store1);
} catch {
}
} else if (inputarray[i] == "-") {
try {
int store1 = stackone.Pop();
int store2 = stackone.Pop();
stackone.Push(store2 - store1);
} catch {
}
} else if (inputarray[i] == "*") {
try {
int store1 = stackone.Pop();
int store2 = stackone.Pop();
stackone.Push(store2 * store1);
} catch {
}
} else if (inputarray[i] == "/") {
try {
int store1 = stackone.Pop();
int store2 = stackone.Pop();
stackone.Push(store2 / store1);
} catch {
}
}
}
while (i++ < end && inputarray[i] != "=" && stackone.Count != 0);
string txtout = TxtInputBox.Text + " " + stackone.Pop().ToString() + Environment.NewLine;
TxtOutputBox.AppendText(txtout);
TxtInputBox.Clear();
}
private void Btn_Calc_Click (object sender, EventArgs e) {
RPNCalc(TxtInputBox, TxtOutputBox);
}
}
}