How to convert from Arabic numbers to English numbers - c#

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();
}

Related

binary search built in method is not working for my window form program c#

I created a program that uses both linear and binary search method. I use string array.
private void linearSearch_Click(object sender, EventArgs e)
{
string target = linearSearchBox.Text;
bool found = false;
for (int x = 0; x < myArray.Length; x++)
{
if (myArray[x] == target)
{
displayBox2.Text = target + " Found at index " + (x + 1) +
"\r\n";
linearSearchBox.Clear();
linearSearchBox.Focus();
return;
}
}
if (!found)
{
displayBox2.Text = "Not Found, try again." + "\r\n";
linearSearchBox.Clear();
linearSearchBox.Focus();
}
}
this will work, however the binary doest not
private void BinarySearch_Click(object sender, EventArgs e)
{
Array.Sort(myArray, 0, emptyPtr);
SearchArray(myArray, binarySearchBox.Text);
}
private void SearchArray(Array array, object value)
{
Array.Sort(myArray, 0, emptyPtr);
string target = binarySearchBox.Text;
int numIndex = Array.BinarySearch(array, target);
if (numIndex < 0)
{
displayBox2.Text = "The element to search for " + target + " is not found.";
}
else if(numIndex >= 0)
{
displayBox2.Text = "The element to search for " + target+ " is at index: " + numIndex;
}
}
test1 test2
Note that the code is performing a binary search in the text box of binarySearchBox, not the value in the text box of ListBox1.
The code that needs to convert the value added to ListBox1 into an Array array for storage.string[]myArray = listBox1.Items.Cast<string>().ToArray();,then search for ListBox1.
Code show as below:
private void BinarySearch_Click(object sender, EventArgs e)
{
string[]myArray = listBox1.Items.Cast<string>().ToArray();
Array.Sort(myArray, 0, emptyPtr);
SearchArray(myArray, binarySearchBox.Text);
}
private void SearchArray(Array array, object value)
{
string[] myArray = listBox1.Items.Cast<string>().ToArray();
Array.Sort(myArray, 0, emptyPtr);
string target = binarySearchBox.Text;
int numIndex = Array.BinarySearch(array, target);
if (numIndex < 0)
{
displayBox2.Text = "The element to search for " + target + " is not found.";
}
else if (numIndex >= 0)
{
displayBox2.Text = "The element to search for " + target + " is at index: " + numIndex;
}
}
private void linearSearch_Click(object sender, EventArgs e)
{
string[] myArray = listBox1.Items.Cast<string>().ToArray();
string target = linearSearchBox.Text;
bool found = false;
for (int x = 0; x < myArray.Length; x++)
{
if (myArray[x] == target)
{
displayBox2.Text = target + " Found at index " + (x + 1) +
"\r\n";
linearSearchBox.Clear();
linearSearchBox.Focus();
return;
}
}
if (!found)
{
displayBox2.Text = "Not Found, try again." + "\r\n";
linearSearchBox.Clear();
linearSearchBox.Focus();
}
}

loading large text file into richtextbox c# [duplicate]

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;
}
}

Event is not firing for the first time

In RichTextBox, I'm trying to fire an event with pressing period ('.') But It's not working for the first time.
If I write "Lorem Ipsum.", It's not working but If I write "Lorem Ipsum ." or "Lorem Ipsum.." It's OK.
PS: I've added the KelimeGuncelle method and GetWordGroupInstances() dictionary also.
Here's the block:
private void rtbMakale_KeyDown(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.OemPeriod)
{
kelimeGuncelle();
}
}
The kelimeGuncelle method:
void kelimeGuncelle()
{
Dictionary<String, int> TekliKelimeGruplari = GetWordGroupInstances(1);
foreach (var item in TekliKelimeGruplari)
{
for (int i = 0; i < lstKelimeler.Items.Count; i++)
{
var kelime = lstKelimeler.Items[i];
string guncellenecekKelime = kelime.ToString().Remove(kelime.ToString().IndexOf(" ( ") - 1);
string gelenKelime = item.Key;
string _guncellenecekKelime = kelime.ToString();
int pFrom = _guncellenecekKelime.IndexOf("(") + 1;
int pTo = _guncellenecekKelime.LastIndexOf("/");
int guncellenecekSayi = Convert.ToInt32(_guncellenecekKelime.Substring(pFrom, pTo - pFrom));
int kFrom = _guncellenecekKelime.IndexOf("/") + 1;
int kTo = _guncellenecekKelime.LastIndexOf(")");
int toplamYazilacakSayi = Convert.ToInt32(_guncellenecekKelime.Substring(kFrom, kTo - kFrom));
int kelimeninSirasi = lstKelimeler.Items.IndexOf(kelime);
if (Equals(guncellenecekKelime, gelenKelime))
{
guncellenecekSayi = item.Value;
lstKelimeler.Items.RemoveAt(kelimeninSirasi);
lstKelimeler.Items.Insert(kelimeninSirasi, guncellenecekKelime + " ( " + guncellenecekSayi + "/" + toplamYazilacakSayi + " )");
//lstKelimeler.Refresh();
}
if (rtbMakale.Text.Contains(guncellenecekKelime) == false)
{
lstKelimeler.Items.RemoveAt(kelimeninSirasi);
lstKelimeler.Items.Insert(kelimeninSirasi, guncellenecekKelime + " ( 0/" + toplamYazilacakSayi + " )");
//lstKelimeler.Refresh();
}
}
}
TekliKelimeGruplari.Clear();
}
And GetWordGroupInstances:
Dictionary<String, int> GetWordGroupInstances(int GroupSize)
{
Dictionary<String, int> WordGroupInstances = new Dictionary<string, int>();
String[] sourceText = GetSourceText().Split(' ');
int pointer = 0;
StringBuilder groupBuilder = new StringBuilder();
while (pointer < sourceText.Length - GroupSize)
{
groupBuilder.Clear();
int offset = pointer + GroupSize;
for (int i = pointer; i < offset; i++)
{
groupBuilder.Append(" ").Append(sourceText[i]);
}
String key = groupBuilder.ToString().Substring(1);
if (!WordGroupInstances.ContainsKey(key))
{
WordGroupInstances.Add(key, 1);
}
else
{
WordGroupInstances[key]++;
}
pointer += 1;
}
return WordGroupInstances;
}
try using a MessageBox.Show("Test"); for testing , maybe something in your kelimeGuncelle() method is wrong.
private void rtbMakale_KeyDown(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.OemPeriod)
{
MessageBox.Show("Test");
}
}
I got it!
In the GetWordGroupInstances, I've changed the while loop. Here:
while (pointer <= sourceText.Length - GroupSize)

UI not updating from asynchronous event

i use the Asynchronous socket Client event to receive message from server.
i receive message from client DataIn(my Event Name) and add to list box ,but not happen to show on UI!
protected void WebSocketClientControl1_OnChatNotification(List < SocketUi > sender) {
ClientScript.RegisterStartupScript(GetType(), "hwa", "javascript:__doPostBack('WebSocketClientControl1','')", true);
}
i cant use the (Response.Redirect & Server.Transfer).
this 2 function have error run time.
i call the javaScript function to show message , not happen on screen.
its my Socket code
public delegate void OnChatNotification(List<SocketUi> sender);
public class WebSocketClientControl : System.Web.UI.Control, IPostBackDataHandler
{
public static ClientService _internalClientService = new ClientService(DServerConfig.ServerAddress.ToString(),
DServerConfig.ServerSoketPort);
public event OnChatNotification OnChatNotification = delegate { };
public WebSocketClientControl()
{
_internalClientService.OnChat += _internalClientService_OnChat;
}
public void Connect(long userID, SocketEnums.EntityType usertype, string username, string key)
{
_internalClientService.Connect(userID, usertype, username, key);
}
private void _internalClientService_OnChat(List<SocketUI.SocketUi> sender)
{
if (OnChatNotification != null)
OnChatNotification(sender);
}
public bool LoadPostData(string postDataKey, NameValueCollection postCollection)
{
String presentValue = postDataKey;
String postedValue = postCollection[postDataKey];
if (presentValue == null || !presentValue.Equals(postedValue))
{
return true;
}
return false;
}
public void RaisePostDataChangedEvent()
{
}
}
its my ui Code
private void WebSocketClientControl1_OnChatNotification(List<SocketUI.SocketUi> sender)
{
foreach (SocketUi socketUi in sender)
{
switch (socketUi.DSocketType)
{
case SocketEnums.DSocketType.Chat:
foreach (SocketUI.tb_Chat chatUi in socketUi.Chats)
{
for (int i = 0; i < ASPxPageControl1.TabPages.Count; i++)
{
if (ASPxPageControl1.TabPages[i].Name == "uxTabPage_" + _channels[i].ID.ToString())
{
switch (chatUi.ChatMessegeType)
{
case (int)Enums.ChatMessegeType.Message:
SetNewMessageOnUi(HelperD.UiChat_To_Tb_Chat(chatUi));
break;
case (int)Enums.ChatMessegeType.Readed:
break;
case (int)Enums.ChatMessegeType.OnLinedUser:
break;
case (int)Enums.ChatMessegeType.OffLinedUser:
break;
case (int)Enums.ChatMessegeType.JoinChannle:
case (int)Enums.ChatMessegeType.LeftChannle:
GetUserChannel(chatUi.ChannelID.ID);
break;
case (int)Enums.ChatMessegeType.TypingUser:
for (int j = 0; j < ASPxPageControl1.TabPages[i].Controls.Count; j++)
{
if (ASPxPageControl1.TabPages[i].Controls[j] is System.Web.UI.WebControls.Label &&
ASPxPageControl1.TabPages[i].Controls[j].ID ==
"uxLabel_Status" + ASPxPageControl1.TabPages[i].DataItem.ToString())
{
System.Web.UI.WebControls.Label uxLabel_StatusTemp = new System.Web.UI.WebControls.Label();
uxLabel_StatusTemp = (System.Web.UI.WebControls.Label)ASPxPageControl1.TabPages[i].Controls[j];
uxLabel_StatusTemp.Text = " درحال تایپ " + socketUi.UserName + "...";
// timer1.Start();
}
}
break;
}//End For
// listBox_Message.Items.Add("Me:=>" + chatUi.Message + "\n\r");
}
}
}//End For
break;
}
}
}
private void SetNewMessageOnUi(UiSideLanguage.Database.Chat.tb_Chat item)
{
ASPxTextBox_Message.Text = "";
for (int i = 0; i < ASPxPageControl1.TabPages.Count; i++)
{
for (int j = 0; j < ASPxPageControl1.TabPages[i].Controls.Count; j++)
{
if (ASPxPageControl1.TabPages[i].Controls[j] is System.Web.UI.WebControls.ListBox && ASPxPageControl1.TabPages[i].Controls[j].ID == "uxListView_Chat" + ASPxPageControl1.TabPages[i].DataItem.ToString())
{
System.Web.UI.WebControls.ListBox userListView = (System.Web.UI.WebControls.ListBox)ASPxPageControl1.TabPages[i].Controls[j];
System.Web.UI.WebControls.ListItem listViewItemTemp = new System.Web.UI.WebControls.ListItem();
if (item.AddUser.ID == Language.CacheEntity.CurrentUser.ID)
{
listViewItemTemp.Text = " :من " + item.Message;
// listViewItemTemp.ForeColor = Color.DarkCyan;
}
else
{
listViewItemTemp.Text = item.AddUser.UserName + " : " + item.Message;
// listViewItemTemp.ForeColor = Color.DarkRed;
}
listViewItemTemp.Value = item.MessageFlagID.ToString();
System.Web.UI.WebControls.ListItem isHaveChatItem = null;
foreach (System.Web.UI.WebControls.ListItem chatitemListView in userListView.Items)
{
if (Language.HelperD.GetLong(chatitemListView.Value) == item.MessageFlagID)
{
isHaveChatItem = chatitemListView;
break;
}
}
if (isHaveChatItem != null)
{
if (item.AddUser.ID == Language.CacheEntity.CurrentUser.ID)
{
isHaveChatItem.Text = " :من " + item.Message;
// isHaveChatItem.ForeColor = Color.DarkCyan;
}
else
{
isHaveChatItem.Text = item.ToUser.UserName + " : " + item.Message;
// isHaveChatItem.ForeColor = Color.DarkRed;
}
isHaveChatItem.Value = item.MessageFlagID.ToString();
}
else
{
userListView.Items.Add(listViewItemTemp);
}
}
}
}
}
This function for Update UI >>> SetNewMessageOnUi
I Create Objects on Runtime.
this code is worked
userListView.Items.Add(listViewItemTemp);
and ListView Have Item But On UI Not set.
all objects in the UpdatePanle

Add text to list when user presses button in Android app?

I am having some trouble with the verse button. i am not sure what I am doing wrong but I need to make it where the user presses the verse button and it adds the textview of the word "Verse" to the list that was created. Please help. What am I doing wrong. This was written for Android using C# in Xamarin by the way.
namespace Songression
{
public class CheckRect{
public int top{ get; set; }
public int height{ get; set; }
}
[Activity (Label = "Songression")]
public class results : Activity, View.IOnTouchListener
{
//CheckBox[] check;
List<LinearLayout> linearSet;
//List<CheckRect> rectList;
ScrollView scrollView;
EditText editText = null;
LinearLayout view;
bool moveOrEdit = false;
int screenWidth;
List<String> checkTextList;
protected override void OnCreate (Bundle bundle)
{
base.OnCreate (bundle);
SetContentView (Resource.Layout.results);
var metrics = Resources.DisplayMetrics;
screenWidth = metrics.WidthPixels;
//var widthInDp = ConvertPixelsToDp(metrics.WidthPixels);
view = FindViewById<LinearLayout> (Resource.Id.linearlayout0);
checkTextList = new List<String>();
checkTextList.Add ("10 bucks in your pocket and barely making it.");
checkTextList.Add ("100 steps to the water");
checkTextList.Add ("18 and going to Hollywood");
checkTextList.Add ("3 years to propose");
String checkTextSet = Intent.GetStringExtra ("MyData") ?? "";
if (checkTextSet == null || checkTextSet == "") {
} else {
String[] textSet = checkTextSet.Split (',');
checkTextList.AddRange (textSet);
}
//Back Button
Button buttonBack = FindViewById<Button> (Resource.Id.buttonBack);
buttonBack.Click += delegate {
Finish();
};
///
//AddLine Button
Button buttonAdd = FindViewById<Button> (Resource.Id.buttonAdd);
buttonAdd.Click += delegate {
addTextPro(false,"");
};
///
//Add Verse
//Button buttonVerse = FindViewById <Button> (Resource.Id.buttonVerse);
//buttonVerse.Click += delegate {
// checkTextList.Add("Verse"));
//};
{
///
//Email Button
Button buttonEmail = FindViewById<Button> (Resource.Id.buttonEmail);
buttonEmail.Click += delegate {
runEmailPro ();
};
scrollView = FindViewById<ScrollView> (Resource.Id.scrollview0);
List<String> resultList = new List<String> ();
int count = checkTextList.Count;//myResources.check_indexSet.Count;
linearSet = new List<LinearLayout> ();
for (int index = 0; index < view.ChildCount; index++) {
view.RemoveViewAt (index);
}
///
//Initiate Rect and Check
if (myResources.isLast == false) {
for (int index = 0; index < count; index++) {
InitiateWidgets (index, false);
}
} else {
var sdCardPath = Android.OS.Environment.ExternalStorageDirectory.Path;
var lastPath = Path.Combine (sdCardPath, "lastlasttxt.txt");
String fileNamePath = Path.Combine (sdCardPath, readFileSdcardFile (lastPath));
String loadData;
if (File.Exists (fileNamePath))
loadData = File.ReadAllText (fileNamePath);
else
return;
String[] splitData = loadData.Split ('\n');
foreach (String item in splitData) {
if (item.CompareTo ("") == 0)
continue;
if (item [0] == 't') {
addTextPro (true, item.Substring (1));
}
if (item [0] == 'c') {
bool bChecked = false;
if (item [1] != '0') {
bChecked = true;
} else {
bChecked = false;
}
InitiateWidgets (0, true, item.Substring (2), bChecked);
}
}
}
///
//save function
Button buttonSave = FindViewById<Button> (Resource.Id.buttonSave);
buttonSave.Click += delegate {
saveResultPro ();
};
///
//move function
Button buttonMove = FindViewById<Button> (Resource.Id.buttonMove);
buttonMove.Text = "Move";
buttonMove.Click += delegate {
removeAllFocus (moveOrEdit);
if (moveOrEdit == false) {
buttonMove.Text = "Edit";
moveOrEdit = true;
} else {
buttonMove.Text = "Move";
moveOrEdit = false;
}
};
//final function
Button buttonFinal = FindViewById<Button> (Resource.Id.buttonFinal);
buttonFinal.Click += delegate {
var fResults = new Intent (this, typeof(finalResults));
fResults.PutExtra ("MyData", getAllInfo ());
StartActivity (fResults);
};
}
}
//wirte the file on the sdcard.
public void writeFileSdcardFile(String path,String write_str,bool bTitle){
if (bTitle == true) {
var sdCardPath = Android.OS.Environment.ExternalStorageDirectory.Path;
var lastPath = Path.Combine(sdCardPath,"lastlasttxt.txt");
if (File.Exists (path) == false) {
File.WriteAllText (path, write_str);
}
else {
String[] existFile = readFileSdcardFile (path).Split('\n');
foreach (String item in existFile) {
if (write_str.Substring (0, write_str.Length - 1).CompareTo (item) == 0) {
File.WriteAllText (lastPath, write_str.Substring (0, write_str.Length - 1));
return;
}
}
File.AppendAllText (path, write_str);
}
File.WriteAllText (lastPath, write_str.Substring(0, write_str.Length - 1));
} else {
File.WriteAllText (path, write_str);
}
}
public String readFileSdcardFile(String path) {
if (File.Exists (path))
return File.ReadAllText (path);
else
return "";
}
public String getAllInfo()
{
String extra = "";
foreach(LinearLayout linear in linearSet)
{
var widgetType = linear.GetChildAt (0).GetType ().ToString ();
if (widgetType.CompareTo ("Android.Widget.EditText") == 0) {
EditText editText = (EditText)linear.GetChildAt (0);
extra += editText.Text + "\n";
} else if (widgetType.CompareTo ("Android.Widget.CheckBox") == 0) {
CheckBox checBox = (CheckBox)linear.GetChildAt (0);
if (checBox.Checked == true)
extra +="1" + checBox.Text + "\n";
else
extra +="0" + checBox.Text + "\n";
}
}
return extra;
}
//
//run email pro
public void runEmailPro(){
var email = new Intent (Android.Content.Intent.ActionSend);
email.PutExtra (Android.Content.Intent.ExtraEmail,
new string[]{"person1#xamarin.com", "person2#xamrin.com"} );
email.PutExtra (Android.Content.Intent.ExtraCc,
new string[]{"person3#xamarin.com"} );
email.PutExtra (Android.Content.Intent.ExtraSubject, "Hello Email");
email.PutExtra (Android.Content.Intent.ExtraText,
getAllInfo());
email.SetType ("message/rfc822");
StartActivity (email);
}
//
// add Text code
public void addTextPro(bool bLast,String textWidget)
{
LinearLayout linear = new LinearLayout (this);
ImageView imgView = new ImageView (this);
imgView.SetImageResource (Resource.Drawable.delete123);
editText = new EditText (this);
editText.SetSingleLine ();
editText.SetWidth(screenWidth - 50);
if (bLast)
editText.Text = textWidget;
if (moveOrEdit == true)
editText.SetOnTouchListener (this);
else
editText.SetOnTouchListener (null);
linear.AddView(editText);
linear.AddView(imgView);
//delete function.
imgView.Click += delegate {
deleteMessage(imgView);
};
linearSet.Add(linear);
view.AddView(linear);
}
//
//delete message
public void deleteMessage(ImageView imgView)
{
var builder = new AlertDialog.Builder(this);
builder.SetTitle("Delete Phrase!");
builder.SetMessage ("Are you sure you would like to delete this phrase?");
builder.SetPositiveButton("Yes", (sender, args) => {
// Yes button
LinearLayout parent = (LinearLayout)imgView.Parent;
parent.Visibility = ViewStates.Invisible;
int childIndex = view.IndexOfChild(parent);
view.RemoveView(parent);
linearSet.Remove(parent);});
builder.SetNegativeButton("No", (sender, args) => {});
builder.SetCancelable(false);
builder.Show ();
}
//
//save Result
public void saveResultPro()
{
var factory = LayoutInflater.From(this);
var builder = new AlertDialog.Builder(this);
builder.SetTitle("Song Name");
EditText songText = new EditText (this);
builder.SetView (songText);
//builder.SetView(factory.Inflate(Resource.Layout.saveDialog,
// FindViewById<ViewGroup>(Resource.Id.saveDialog)));
builder.SetPositiveButton("OK", (sender, args) => {
var sdCardPath = Android.OS.Environment.ExternalStorageDirectory.Path;
//EditText songText = FindViewById<EditText> (Resource.Id.projectName);
var textPath = Path.Combine(sdCardPath,songText.Text);
var textTitlePath = Path.Combine(sdCardPath,"Titles.txt");
String saveData = "";
foreach(LinearLayout linear in linearSet)
{
var widgetType = linear.GetChildAt (0).GetType ().ToString ();
if (widgetType.CompareTo ("Android.Widget.EditText") == 0) {
EditText editText = (EditText)linear.GetChildAt (0);
saveData += "t" + editText.Text + "\n";
} else if (widgetType.CompareTo ("Android.Widget.CheckBox") == 0) {
CheckBox checBox = (CheckBox)linear.GetChildAt (0);
if (checBox.Checked == true)
saveData += "c1" + checBox.Text + "\n";
else
saveData += "c0" + checBox.Text + "\n";
}
}
writeFileSdcardFile(textTitlePath,songText.Text + "\n",true);
writeFileSdcardFile(textPath,saveData,false);
});
builder.SetNegativeButton("Cancel", (sender, args) => {});
builder.SetCancelable(false);
builder.Show ();
}
//remove All focus
public void removeAllFocus(bool flag){
View.IOnTouchListener context = null;
if (flag == false){
context = this;
}
else{
context = null;
}
foreach (LinearLayout linear in linearSet) {
var widgetType = linear.GetChildAt (0).GetType ().ToString ();
if (widgetType.CompareTo ("Android.Widget.EditText") == 0) {
EditText editText = (EditText)linear.GetChildAt (0);
editText.SetOnTouchListener (context);
} else if (widgetType.CompareTo ("Android.Widget.CheckBox") == 0) {
CheckBox checBox = (CheckBox)linear.GetChildAt (0);
checBox.SetOnTouchListener (context);
}
}
scrollView.SetOnTouchListener (context);
}
//
//initiate widgets
public void InitiateWidgets(int index,bool bLast,String widgetText = "", bool bSel = false){
LinearLayout linear = new LinearLayout (this);
CheckBox check = new CheckBox(this);
ImageView imgView = new ImageView (this);
//delete function.
imgView.Click += delegate {
deleteMessage(imgView);
};
if (bLast == false) {
//int stringIndex = Resource.String.checkname0 + myResources.check_indexSet [index];
check.Text = checkTextList[index];
if (index < 4) {
if (myResources.check_index [index] == 1)
check.Checked = true;
else {
check.Checked = false;
}
} else {
check.Checked = true;
}
} else {
check.Text = widgetText;
check.Checked = bSel;
}
check.SetWidth (screenWidth - 55);
check.SetOnTouchListener (null);
imgView.SetImageResource (Resource.Drawable.delete123);
linear.AddView (check);
linear.AddView (imgView);
linearSet.Add(linear);
view.AddView (linear);
scrollView.SetOnTouchListener (null);
}
//
//Touch Event
float _viewY = 0;
//bool flag = false;
bool check_flag = false;
LinearLayout parentLayout;
int selTop;
int selBottom;
bool downFlag = false;
public bool OnTouch(View v, MotionEvent e)
{
switch (e.Action)
{
case MotionEventActions.Down:
if (v != scrollView) {
_viewY = e.GetY ();
parentLayout = (LinearLayout)v.Parent;
selTop = parentLayout.Top;
selBottom = parentLayout.Bottom;
check_flag = true;
downFlag = true;
}
break;
case MotionEventActions.Move:
if (v == scrollView && downFlag == true) {
var top = (int)(e.GetY () - _viewY);
var bottom = (int)(top + 55);
parentLayout.Layout (parentLayout.Left, top, parentLayout.Right, bottom);
check_flag = false;
}
break;
case MotionEventActions.Up:
if (downFlag == false)
return true;
if (parentLayout == null)
return true;
int originalPos = 0;
int placePos = -1;
downFlag = false;
if (parentLayout.GetChildAt(0).GetType ().ToString ().CompareTo ("Android.Widget.CheckBox") == 0) {
if (check_flag == true) {
CheckBox selCheck = (CheckBox)parentLayout.GetChildAt (0);
if (selCheck.Checked == false) {
selCheck.Checked = true;
} else {
selCheck.Checked = false;
}
check_flag = false;
return true;
}
}
if (parentLayout.GetChildAt(0).GetType ().ToString ().CompareTo ("Android.Widget.EditText") == 0) {
if (check_flag == true) {
EditText selText = (EditText)parentLayout.GetChildAt (0);
check_flag = false;
return true;
}
}
if (v == scrollView) {
int linearCount = linearSet.Count;
int index;
for (index = 0; index < linearCount; index++) {
if (parentLayout == linearSet [index]) {
originalPos = index;
break;
}
}
//Laying position.
for (index = 0; index < linearCount; index++) {
if (originalPos == index)
continue;
if (linearSet[originalPos].Top < linearSet [index].Top) {
if (originalPos == index - 1) {
linearSet[originalPos].Layout (linearSet[originalPos].Left,
selTop, linearSet[originalPos].Right,
selBottom);
return true;
} else {
if (index > originalPos) {
placePos = index - 1;
break;
} else {
placePos = index;
break;
}
}
}
/*if (linearSet [originalPos].Top == linearSet [index].Top) {
linearSet[originalPos].Layout (linearSet[originalPos].Left,
selTop, linearSet[originalPos].Right,
selBottom);
return true;
}*/
}
//Is original pos?
if ((originalPos == linearCount - 1) && (placePos == -1)) {
linearSet[originalPos].Layout (linearSet[originalPos].Left, selTop,
linearSet[originalPos].Right, selBottom);
return true;
}
if (placePos == -1)
placePos = linearCount - 1;
//Change the position on the result page.
int orgTop;
int orgBottom;
orgTop = linearSet [originalPos].Top;
orgBottom = linearSet [originalPos].Bottom;
linearSet [originalPos].Layout (linearSet[originalPos].Left, linearSet [placePos].Top,
linearSet[originalPos].Right, linearSet [placePos].Bottom);
LinearLayout tempLinear = linearSet [originalPos];
if (originalPos >= placePos) {
for (index = originalPos - 1; index >= placePos; index--) {
linearSet [index].Layout (linearSet[originalPos].Left, linearSet [index + 1].Top,
linearSet[originalPos].Right, linearSet [index + 1].Bottom);
linearSet [index + 1] = linearSet [index];
}
} else {
for (index = originalPos + 1; index <= placePos; index++){
linearSet [index].Layout (linearSet[originalPos].Left, linearSet [index - 1].Top,
linearSet[originalPos].Right, linearSet [index - 1].Bottom);
linearSet [index - 1] = linearSet [index];
}
}
linearSet [placePos] = tempLinear;
linearSet [placePos].Layout (linearSet[placePos].Left, orgTop,
linearSet[placePos].Right, orgBottom);
view.RemoveViews (0, view.ChildCount);
for (index = 0; index < linearSet.Count; index++) {
view.AddView(linearSet[index]);
}
}
break;
}
return true;
}
}
}
You missed to register listener to the Button click and override onClick

Categories

Resources