I am trying to pass data between two activities using Intents, but at the moment when I try to get the data from the previous activity it just gives me a value of 0 when I print it on the view.
I've searched for ages, but everything I find doesn't exist or is deprecated :(
FirstActivity:
using System;
using Android.App;
using Android.Content;
using Android.Media;
using Android.OS;
using Android.Widget;
namespace PayrollCalculator
{
[Activity(Label = "FirstActivity")]
public class FirstActivity : Activity
{
protected override void OnCreate(Bundle savedInstanceState)
{
base.OnCreate(savedInstanceState);
SetContentView(Resource.Layout.first_activity_layout);
//payroll month
Spinner spinner = FindViewById<Spinner>(Resource.Id.monthSpinner);
var adapter = ArrayAdapter.CreateFromResource(this, Resource.Array.month_array, Android.Resource.Layout.SimpleSpinnerItem);
adapter.SetDropDownViewResource(Android.Resource.Layout.SimpleSpinnerDropDownItem);
spinner.Adapter = adapter;
int monthsRemaining = 11;
if (spinner.SelectedItem.ToString() == "January")
{
monthsRemaining = 11;
}
if (spinner.SelectedItem.ToString() == "Febuary")
{
monthsRemaining = 10;
}
if (spinner.SelectedItem.ToString() == "March")
{
monthsRemaining = 9;
}
if (spinner.SelectedItem.ToString() == "April")
{
monthsRemaining = 8;
}
if (spinner.SelectedItem.ToString() == "May")
{
monthsRemaining = 7;
}
if (spinner.SelectedItem.ToString() == "June")
{
monthsRemaining = 6;
}
if (spinner.SelectedItem.ToString() == "July")
{
monthsRemaining = 5;
}
if (spinner.SelectedItem.ToString() == "August")
{
monthsRemaining = 4;
}
if (spinner.SelectedItem.ToString() == "September")
{
monthsRemaining = 3;
}
if (spinner.SelectedItem.ToString() == "October")
{
monthsRemaining = 2;
}
if (spinner.SelectedItem.ToString() == "November")
{
monthsRemaining = 1;
}
if (spinner.SelectedItem.ToString() == "December")
{
monthsRemaining = 0;
}
//marital status
Spinner spinner2 = FindViewById<Spinner>(Resource.Id.statusSpinner);
var adapter2 = ArrayAdapter.CreateFromResource(this, Resource.Array.status_array, Android.Resource.Layout.SimpleSpinnerItem);
adapter2.SetDropDownViewResource(Android.Resource.Layout.SimpleSpinnerDropDownItem);
spinner2.Adapter = adapter2;
//disabled
RadioButton disabledTrue = FindViewById<RadioButton>(Resource.Id.radioDisabledTrue);
RadioButton disabledFalse = FindViewById<RadioButton>(Resource.Id.radioDisabledFalse);
//spouse disabled
EditText errorView = FindViewById<EditText>(Resource.Id.erroreditview);
RadioButton spouseDisabledTrue = FindViewById<RadioButton>(Resource.Id.radioSpouseDisabledTrue);
RadioButton spouseDisabledFalse = FindViewById<RadioButton>(Resource.Id.radioSpouseDisabledFalse);
spouseDisabledTrue.Click += (sender, e) =>
{
disabledSpouseCan();
};
spouseDisabledFalse.Click += (sender, e) =>
{
disabledSpouseCan();
};
//kidsunder18 or in education 2000
EditText kidsU18 = FindViewById<EditText>(Resource.Id.u18kids);
int.TryParse(kidsU18.Text, out int _kidsU18);
//over 18 HE 8000
EditText over18inHE = FindViewById<EditText>(Resource.Id.over18inHE);
int.TryParse(over18inHE.Text, out int _over18inHE);
//disabled 6000
EditText disabledChildren = FindViewById<EditText>(Resource.Id.disabledChildren);
int.TryParse(disabledChildren.Text, out int _disabledChildren);
//disabled HE 14000
EditText disabledChildreninHE = FindViewById<EditText>(Resource.Id.disabledChildreninHE);
int.TryParse(disabledChildreninHE.Text, out int _disabledChildreninHE);
double disabledDeduction = 0.00;
if (disabledTrue.Checked == true)
{
disabledDeduction = 6000.00;
}
double disabledSpouseDeduction = 0.00;
if (spouseDisabledTrue.Checked == true)
{
disabledSpouseDeduction = 3500.00;
}
double spouseNoIncomeDeduction = 0.00;
if (spinner2.SelectedItem.ToString() == "Married and spouse not working")
{
spouseNoIncomeDeduction = 4000.00;
}
double totalFamilyDeductions = (_kidsU18 * 2000) + (_over18inHE * 8000) + (_disabledChildren * 6000) + (_disabledChildreninHE * 14000) + disabledDeduction + disabledSpouseDeduction + spouseNoIncomeDeduction;
Button _firstContinue = FindViewById<Button>(Resource.Id.continuePayroll1);
_firstContinue.Click += (sender, e) =>
{
if (disabledSpouseCan() == false)
{
Toast toast = Toast.MakeText(this, "Check the error above", ToastLength.Short);
toast.Show();
}
else
{
PlayButton_Click(sender, e);
Intent intent = new Intent(this, typeof(SecondActivity));
intent.PutExtra("totalFamilyDeductions", totalFamilyDeductions);
intent.PutExtra("monthsRemaining", monthsRemaining);
StartActivity(intent);
}
};
void PlayButton_Click(object sender, EventArgs e)
{
MediaPlayer _player = MediaPlayer.Create(this, Resource.Drawable.buttonclick);
_player.Start();
}
bool disabledSpouseCan()
{
if ((spinner2.SelectedItem.ToString() == "Single" | spinner2.SelectedItem.ToString() == "Divorce/Widower/Widow") && (spouseDisabledTrue.Checked == true))
{
errorView.Error = "You don't have a spouse";
return false;
}
else
{
errorView.Error = null;
return true;
}
}
}
}
}
SecondActivity:
using System;
using System.Text.RegularExpressions;
using Android.App;
using Android.Content;
using Android.Media;
using Android.OS;
using Android.Text;
using Android.Widget;
namespace PayrollCalculator
{
[Activity(Label = "SecondActivity")]
public class SecondActivity : Activity
{
protected override void OnCreate(Bundle savedInstanceState)
{
base.OnCreate(savedInstanceState);
SetContentView(Resource.Layout.second_activity_layout);
//currentmonthremu
EditText currentMonthRemuneration_ = FindViewById<EditText>(Resource.Id.currentMonthRemuneration);
currentMonthRemuneration_.SetFilters(new IInputFilter[] { new DecimalDigitsInputFilter(12, 2) });
double _currentMonthRemuneration = 0.00;
currentMonthRemuneration_.AfterTextChanged += (sender, args) =>
{
double.TryParse(currentMonthRemuneration_.Text, out _currentMonthRemuneration);
};
//EPF
EditText EPFContribution_ = FindViewById<EditText>(Resource.Id.EPFContribution);
EPFContribution_.SetFilters(new IInputFilter[] { new DecimalDigitsInputFilter(12, 2) });
double _EPFContribution = 0.00;
EPFContribution_.AfterTextChanged += (sender, args) =>
{
double.TryParse(EPFContribution_.Text, out _EPFContribution);
Validate(_EPFContribution, 4000, EPFContribution_);
};
//BIK
EditText BIK_ = FindViewById<EditText>(Resource.Id.BIK);
BIK_.SetFilters(new IInputFilter[] { new DecimalDigitsInputFilter(12, 2) });
double _BIK = 0.00;
BIK_.AfterTextChanged += (sender, args) =>
{
double.TryParse(BIK_.Text, out _BIK);
};
//VOLA
EditText VOLA_ = FindViewById<EditText>(Resource.Id.VOLA);
VOLA_.SetFilters(new IInputFilter[] { new DecimalDigitsInputFilter(12, 2) });
double _VOLA = 0.00;
VOLA_.AfterTextChanged += (sender, args) =>
{
double.TryParse(VOLA_.Text, out _VOLA);
};
double _EPFCombined =+ _EPFContribution;
//this is where I try to get the data from the previous activity to display on my layout
double _totalFamilyDeductions = Intent.GetDoubleExtra("totalFamilyDeductions", 0.00);
TextView textView111 = FindViewById<TextView>(Resource.Id.textView111);
textView111.Text = "" + _totalFamilyDeductions;
Button _secondContinue = FindViewById<Button>(Resource.Id.continuePayroll2);
_secondContinue.Click += (sender, e) =>
{
if (Validate(_EPFContribution, 4000, EPFContribution_) == false)
{
Toast toast = Toast.MakeText(this, "Please make sure EPF is below RM4000", ToastLength.Short);
toast.Show();
}
else
{
int _monthsRemaining = Intent.GetIntExtra("monthsRemaining", 11);
PlayButton_Click(sender, e);
Intent intent = new Intent(this, typeof(ThirdActivity));
intent.PutExtra("currentMonthRemuneration", _currentMonthRemuneration);
intent.PutExtra("EPFContribution", _EPFContribution);
intent.PutExtra("BIK", _BIK);
intent.PutExtra("VOLA", _VOLA);
intent.PutExtra("EPFCombined", _EPFCombined);
intent.PutExtra("totalFamilyDeductions", _totalFamilyDeductions);
intent.PutExtra("monthsRemaining", _monthsRemaining);
StartActivity(intent);
}
};
void PlayButton_Click(object sender, EventArgs e)
{
MediaPlayer _player = MediaPlayer.Create(this, Resource.Drawable.buttonclick);
_player.Start();
}
}
bool Validate(double name, double value, EditText editText)
{
if (name > value)
{
editText.Error = "Cannot be greater than " + value;
return false;
}
else
{
return true;
}
}
}
public class DecimalDigitsInputFilter : Java.Lang.Object, IInputFilter
{
readonly string regexStr = string.Empty;
public DecimalDigitsInputFilter(int digitsBeforeZero, int digitsAfterZero)
{
regexStr = "^[0-9]{0," + digitsBeforeZero + "}([.][0-9]{0," + (digitsAfterZero - 1) + "})?$";
}
public Java.Lang.ICharSequence FilterFormatted(Java.Lang.ICharSequence source, int start, int end, ISpanned dest, int dstart, int dend)
{
Regex regex = new Regex(regexStr);
if (regex.IsMatch(dest.ToString()) || dest.ToString().Equals(""))
{
if (dest.ToString().Length < 12 && source.ToString() != ".")
{
return new Java.Lang.String(source.ToString());
}
else if (source.ToString() == ".")
{
return new Java.Lang.String(source.ToString());
}
else if (dest.ToString().Length >= 13 && dest.ToString().Length <= 20)
{
return new Java.Lang.String(source.ToString());
}
else
{
return new Java.Lang.String(string.Empty);
}
}
return new Java.Lang.String(string.Empty);
}
}
}
When I try to display _totalFamilyDeductions on the view It just displays 0.
Any help Appreciated!
From your code above I assume that it should be:
private int _kidsU18;
private int _over18inHE;
private int _disabledChildren;
private int _disabledChildreninHE;
double disabledDeduction = 0.00;
double disabledSpouseDeduction = 0.00;
double spouseNoIncomeDeduction = 0.00;
protected override void OnCreate(Bundle savedInstanceState)
{
base.OnCreate(savedInstanceState);
SetContentView(Resource.Layout.first_activity_layout);
//payroll month
Spinner spinner = FindViewById<Spinner>(Resource.Id.monthSpinner);
var adapter = ArrayAdapter.CreateFromResource(this, Resource.Array.month_array, Android.Resource.Layout.SimpleSpinnerItem);
adapter.SetDropDownViewResource(Android.Resource.Layout.SimpleSpinnerDropDownItem);
spinner.Adapter = adapter;
int monthsRemaining = 11;
if (spinner.SelectedItem.ToString() == "January")
{
monthsRemaining = 11;
}
if (spinner.SelectedItem.ToString() == "Febuary")
{
monthsRemaining = 10;
}
if (spinner.SelectedItem.ToString() == "March")
{
monthsRemaining = 9;
}
if (spinner.SelectedItem.ToString() == "April")
{
monthsRemaining = 8;
}
if (spinner.SelectedItem.ToString() == "May")
{
monthsRemaining = 7;
}
if (spinner.SelectedItem.ToString() == "June")
{
monthsRemaining = 6;
}
if (spinner.SelectedItem.ToString() == "July")
{
monthsRemaining = 5;
}
if (spinner.SelectedItem.ToString() == "August")
{
monthsRemaining = 4;
}
if (spinner.SelectedItem.ToString() == "September")
{
monthsRemaining = 3;
}
if (spinner.SelectedItem.ToString() == "October")
{
monthsRemaining = 2;
}
if (spinner.SelectedItem.ToString() == "November")
{
monthsRemaining = 1;
}
if (spinner.SelectedItem.ToString() == "December")
{
monthsRemaining = 0;
}
//marital status
Spinner spinner2 = FindViewById<Spinner>(Resource.Id.statusSpinner);
var adapter2 = ArrayAdapter.CreateFromResource(this, Resource.Array.status_array, Android.Resource.Layout.SimpleSpinnerItem);
adapter2.SetDropDownViewResource(Android.Resource.Layout.SimpleSpinnerDropDownItem);
spinner2.Adapter = adapter2;
spinner2.ItemSelected += Spinner2_ItemSelected;
//disabled
RadioButton disabledTrue = FindViewById<RadioButton>(Resource.Id.radioDisabledTrue);
disabledTrue.CheckedChange += RadioButton_CheckedChanged;
RadioButton disabledFalse = FindViewById<RadioButton>(Resource.Id.radioDisabledFalse);
//spouse disabled
EditText errorView = FindViewById<EditText>(Resource.Id.erroreditview);
RadioButton spouseDisabledTrue = FindViewById<RadioButton>(Resource.Id.radioSpouseDisabledTrue);
spouseDisabledTrue.CheckedChange += RadioButton_CheckedChanged;
RadioButton spouseDisabledFalse = FindViewById<RadioButton>(Resource.Id.radioSpouseDisabledFalse);
spouseDisabledTrue.Click += (sender, e) =>
{
disabledSpouseCan();
};
spouseDisabledFalse.Click += (sender, e) =>
{
disabledSpouseCan();
};
//kidsunder18 or in education 2000
EditText kidsU18 = FindViewById<EditText>(Resource.Id.u18kids);
kidsU18.TextChanged += EditText_TextChanged;
//over 18 HE 8000
EditText over18inHE = FindViewById<EditText>(Resource.Id.over18inHE);
over18inHE.TextChanged += EditText_TextChanged;
//disabled 6000
EditText disabledChildren = FindViewById<EditText>(Resource.Id.disabledChildren);
disabledChildren.TextChanged += EditText_TextChanged;
//disabled HE 14000
EditText disabledChildreninHE = FindViewById<EditText>(Resource.Id.disabledChildreninHE);
disabledChildreninHE.TextChanged += EditText_TextChanged;
Button _firstContinue = FindViewById<Button>(Resource.Id.continuePayroll1);
_firstContinue.Click += (sender, e) =>
{
if (disabledSpouseCan() == false)
{
Toast toast = Toast.MakeText(this, "Check the error above", ToastLength.Short);
toast.Show();
}
else
{
PlayButton_Click(sender, e);
double totalFamilyDeductions = (_kidsU18 * 2000) + (_over18inHE * 8000) + (_disabledChildren * 6000) + (_disabledChildreninHE * 14000) + disabledDeduction + disabledSpouseDeduction + spouseNoIncomeDeduction;
Intent intent = new Intent(this, typeof(SecondActivity));
intent.PutExtra("totalFamilyDeductions", totalFamilyDeductions);
intent.PutExtra("monthsRemaining", monthsRemaining);
StartActivity(intent);
}
};
void PlayButton_Click(object sender, EventArgs e)
{
MediaPlayer _player = MediaPlayer.Create(this, Resource.Drawable.buttonclick);
_player.Start();
}
bool disabledSpouseCan()
{
if ((spinner2.SelectedItem.ToString() == "Single" | spinner2.SelectedItem.ToString() == "Divorce/Widower/Widow") && (spouseDisabledTrue.Checked == true))
{
errorView.Error = "You don't have a spouse";
return false;
}
else
{
errorView.Error = null;
return true;
}
}
}
private void Spinner2_ItemSelected(object sender, AdapterView.ItemSelectedEventArgs e)
{
if (((Spinner)sender).SelectedItem.ToString() == "Married and spouse not working")
{
spouseNoIncomeDeduction = 4000.00;
}
}
private void RadioButton_CheckedChanged(object sender, CompoundButton.CheckedChangeEventArgs e)
{
RadioButton radioButton = sender as RadioButton;
if (e.IsChecked)
{
switch (radioButton.Id)
{
case Resource.Id.radioDisabledTrue:
disabledDeduction = 6000.00;
break;
break;
case Resource.Id.radioSpouseDisabledTrue:
disabledSpouseDeduction = 3500.00;
break;
default:
break;
}
}
}
private void EditText_TextChanged(object sender, TextChangedEventArgs e)
{
EditText editText = sender as EditText;
switch (editText.Id)
{
case Resource.Id.u18kids:
_kidsU18 = int.Parse(editText.Text);
break;
case Resource.Id.over18inHE:
_over18inHE = int.Parse(editText.Text);
break;
case Resource.Id.disabledChildren:
_disabledChildren = int.Parse(editText.Text);
break;
case Resource.Id.disabledChildreninHE:
_disabledChildreninHE = int.Parse(editText.Text);
break;
default:
break;
}
}
Since I don't know your logic, you may need to adjust it yourself, but one thing to be clear is that if you change the data while typing or selecting, you need to change the data in the corresponding event.
Related
How do I change the autocomplete on a TextBox? I want that when I type a string, the box suggest items containing that string instead of starting with.
My code is:
class MyClass
{
private AutoCompleteStringCollection autoCompleteList = new AutoCompleteStringCollection();
public MyClass()
{
InitializeComponent();
autoCompleteList.AddRange(ListNames.Select(x=>x.Name).ToArray());
textBoxName.AutoCompleteCustomSource = autoCompleteList;
textBoxName.AutoCompleteSource = AutoCompleteSource.CustomSource;
textBoxName.AutoCompleteMode = AutoCompleteMode.Suggest;
textBoxName.KeyDown += TextBoxtextName_KeyDown;
}
private void TextBoxClient_KeyDown(object sender, KeyEventArgs e)
{
if (e.KeyData == Keys.Enter)
{
this.Name = (sender as TextBox).Text;
}
}
}
What I want:
Looking at your code you have everything you need but 1 line of code. That line is:
This will only work if the start of a string is entered
//Suggestion only
textBoxName.AutoCompleteMode = AutoCompleteMode.Suggest;
//Suggest and autocomplete
textBoxName.AutoCompleteMode = AutoCompleteMode.SuggestAppend;
This will work as a contains method but works with a custom control
You can also make a custom textbox control that fits your needs.
Custom textbox class:
public class AutoCompleteTextBox : TextBox
{
private ListBox _listBox;
private bool _isAdded;
private String[] _values;
private String _formerValue = String.Empty;
public AutoCompleteTextBox()
{
InitializeComponent();
ResetListBox();
}
private void InitializeComponent()
{
_listBox = new ListBox();
this.KeyDown += this_KeyDown;
this.KeyUp += this_KeyUp;
}
private void ShowListBox()
{
if (!_isAdded)
{
Parent.Controls.Add(_listBox);
_listBox.Left = Left;
_listBox.Top = Top + Height;
_isAdded = true;
}
_listBox.Visible = true;
_listBox.BringToFront();
}
private void ResetListBox()
{
_listBox.Visible = false;
}
private void this_KeyUp(object sender, KeyEventArgs e)
{
UpdateListBox();
}
private void this_KeyDown(object sender, KeyEventArgs e)
{
switch (e.KeyCode)
{
case Keys.Enter:
case Keys.Tab:
{
if (_listBox.Visible)
{
Text = _listBox.SelectedItem.ToString();
ResetListBox();
_formerValue = Text;
this.Select(this.Text.Length, 0);
e.Handled = true;
}
break;
}
case Keys.Down:
{
if ((_listBox.Visible) && (_listBox.SelectedIndex < _listBox.Items.Count - 1))
_listBox.SelectedIndex++;
e.Handled = true;
break;
}
case Keys.Up:
{
if ((_listBox.Visible) && (_listBox.SelectedIndex > 0))
_listBox.SelectedIndex--;
e.Handled = true;
break;
}
}
}
protected override bool IsInputKey(Keys keyData)
{
switch (keyData)
{
case Keys.Tab:
if (_listBox.Visible)
return true;
else
return false;
default:
return base.IsInputKey(keyData);
}
}
private void UpdateListBox()
{
if (Text == _formerValue)
return;
_formerValue = this.Text;
string word = this.Text;
if (_values != null && word.Length > 0)
{
string[] matches = Array.FindAll(_values,
x => (x.ToLower().Contains(word.ToLower())));
if (matches.Length > 0)
{
ShowListBox();
_listBox.BeginUpdate();
_listBox.Items.Clear();
Array.ForEach(matches, x => _listBox.Items.Add(x));
_listBox.SelectedIndex = 0;
_listBox.Height = 0;
_listBox.Width = 0;
Focus();
using (Graphics graphics = _listBox.CreateGraphics())
{
for (int i = 0; i < _listBox.Items.Count; i++)
{
if (i < 20)
_listBox.Height += _listBox.GetItemHeight(i);
// it item width is larger than the current one
// set it to the new max item width
// GetItemRectangle does not work for me
// we add a little extra space by using '_'
int itemWidth = (int)graphics.MeasureString(((string)_listBox.Items[i]) + "_", _listBox.Font).Width;
_listBox.Width = (_listBox.Width < itemWidth) ? itemWidth : this.Width; ;
}
}
_listBox.EndUpdate();
}
else
{
ResetListBox();
}
}
else
{
ResetListBox();
}
}
public String[] Values
{
get
{
return _values;
}
set
{
_values = value;
}
}
public List<String> SelectedValues
{
get
{
String[] result = Text.Split(new[] { ' ' }, StringSplitOptions.RemoveEmptyEntries);
return new List<String>(result);
}
}
}
Usage:
string[] nameArray = { "name1", "name2", "name3", "bla name" };
AutoCompleteTextBox tb = new AutoCompleteTextBox();
tb.Values = nameArray;
tb.Location = new Point(10,10);
tb.Size = new Size(25,75);
this.Controls.Add( tb );
I got the code for the custom control from: SO Question - Autocomplete contains
I am unsure how to ask this question as I can't quite well translate it.
I am currently working on my own Windows Form Application that will calculate the dimensions of a given package in inches (written all together in string format) and calculate the dimensions in centimeters, milimeters or even meters and at this point I was wondering what if someone entered wrong dimensions and given measures can not be parsed.
Something like Environment.Exit(), but without closing the application just stopping calculations and writing a message that an error has occured.
If there is a question like this answered, please do link it because I haven't been able to find it.
namespace PretvaranjeDimenzija
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
public double mjera = 1;
public bool pogreska = false;
public string mjeraKratica = " cm";
public string dimenzijeIspis = "";
private void buttonIzracunaj_Click(object sender, EventArgs e)
{
string dim = textBoxDimenzije.Text;
if (dim.Contains('.'))
{
dim = dim.Replace('.', ',');
}
if (dim.Length != 0)
{
if (dim.IndexOf('x') != -1)
{
string[] multiDim = dim.Split('x');
double[] multiDimCentimetara = new double[multiDim.Length];
bool[] uspjeh = new bool[multiDim.Length];
for (int i = 0; i < multiDim.Length; i++)
{
uspjeh[i] = double.TryParse(multiDim[i], out multiDimCentimetara[i]);
if (uspjeh[i] == false)
{
pogreska = true;
goto kraj;
}
}
kraj:
if (pogreska == true)
{
MessageBox.Show("Doslo je do pogreske!");
pogreska = false;
}
else
{
double[] dimenzije = new double[multiDim.Length];
for (int i = 0; i < dimenzije.Length; i++)
{
dimenzije[i] = multiDimCentimetara[i] * 2.54 * mjera;
if (i == dimenzije.Length - 1)
{
dimenzijeIspis += dimenzije[i].ToString() + mjeraKratica;
}
else
{
dimenzijeIspis += dimenzije[i].ToString() + "x";
}
}
textBoxIspisDimenzija.Text = dimenzijeIspis;
dimenzijeIspis = "";
}
}
else
{
double dimCentimetara;
if(double.TryParse(dim, out dimCentimetara))
{
double dimenzija = dimCentimetara * 2.54 * mjera;
dimenzijeIspis = dimenzija.ToString() + mjeraKratica;
textBoxIspisDimenzija.Text = dimenzijeIspis;
dimenzijeIspis = "";
}
else
{
MessageBox.Show("Doslo je do pogreske!");
return;
}
}
}
}
private void radioButton1_CheckedChanged(object sender, EventArgs e)
{
mjera = 0.01;
mjeraKratica = " m";
if (radioButton2.Checked == true)
{
radioButton2.Checked = false;
radioButton1.Checked = true;
}
if (radioButton3.Checked == true)
{
radioButton3.Checked = false;
radioButton1.Checked = true;
}
}
private void radioButton2_CheckedChanged(object sender, EventArgs e)
{
mjera = 1;
mjeraKratica = " cm";
if (radioButton1.Checked == true)
{
radioButton1.Checked = false;
radioButton2.Checked = true;
}
if (radioButton3.Checked == true)
{
radioButton3.Checked = false;
radioButton2.Checked = true;
}
}
private void radioButton3_CheckedChanged(object sender, EventArgs e)
{
mjera = 10;
mjeraKratica = " mm";
if (radioButton2.Checked == true)
{
radioButton2.Checked = false;
radioButton3.Checked = true;
}
if (radioButton1.Checked == true)
{
radioButton1.Checked = false;
radioButton3.Checked = true;
}
}
}
It should be pretty simple, depending on your requirements. For example, you could just use a basic if block in your method.
void CalculateStuff()
{
// Get input. Do stuff.
if (IsInvalid)
{
MessageBox.Show("You did a bad thing.");
return; // exit the method.
}
// now that we know the input is good, do other stuff.
}
Substitute IsInvalid with whatever check condition you want that will return true if the input is not valid.
I have a list of numberes, and I want to make a RichTextBox with autocomplete, so when the user start typing a number, it will give him autocomplete options from the list.
And I want it to be in a RichTextBox because I want the user to be able writing each number in a new line in the RichTextBox, so everytime the user presses enter, it will do the whole autocomplete thing all over again.
I don't really have an idea how to et this ting done.
any help would be very thankfull.
Thanks
I'll paste the code here. I never got the positioning of the box correct, so you will have to play around with the YOffset and the XOffset.
In your form OnLoad:
intellisenseRichTextBox.IntellisenseWords = new string[] { "Test", "Foo", "Bar", "Supercalifragilisticexpialidocious" };
intellisenseRichTextBox.YOffset = 132;
intellisenseRichTextBox.XOffset = 70;
And the classes:
public class NotificationForm : Form
{
public NotificationForm()
{
this.ShowInTaskbar = false;
//this.Enabled = true;
this.FormBorderStyle = FormBorderStyle.None;
}
protected override bool ShowWithoutActivation
{
get
{
return true;
}
}
protected override CreateParams CreateParams
{
get
{
CreateParams baseParams = base.CreateParams;
const int WS_EX_NOACTIVATE = 0x08000000;
const int WS_EX_TOOLWINDOW = 0x00000080;
baseParams.ExStyle |= (int)(WS_EX_NOACTIVATE | WS_EX_TOOLWINDOW);
return baseParams;
}
}
}
public class RichTextBoxIntellisense : RichTextBox
{
private NotificationForm intelliAutoCompleteForm;
private ListBox intelliAutoCompleteListBox;
private bool IsNotificationFormShowing;
private bool IsFromReplaceTab;
private bool IsFromMouseClick;
private int _suggestionCount = 20;
public string[] IntellisenseWords { get; set; }
public int YOffset { get; set; }
public int XOffset { get; set; }
public int SuggestionCount
{
get
{
return _suggestionCount;
}
set
{
_suggestionCount = value;
}
}
public RichTextBoxIntellisense()
{
this.AcceptsTab = true;
this.YOffset = 30;
intelliAutoCompleteForm = new NotificationForm();
intelliAutoCompleteForm.Size = new Size(200, 200);
intelliAutoCompleteForm.TopMost = true;
intelliAutoCompleteListBox = new ListBox();
intelliAutoCompleteListBox.Dock = DockStyle.Fill;
intelliAutoCompleteForm.Controls.Add(intelliAutoCompleteListBox);
this.TextChanged += RichTextBoxIntellisense_TextChanged;
this.KeyDown += RichTextBoxIntellisense_KeyDown;
this.KeyPress += RichTextBoxIntellisense_KeyPress;
this.SelectionChanged += RichTextBoxIntellisense_SelectionChanged;
intelliAutoCompleteListBox.Click += IntelliAutoCompleteListBox_Click;
intelliAutoCompleteListBox.SelectedIndexChanged += IntelliAutoCompleteListBox_SelectedIndexChanged;
intelliAutoCompleteForm.Show();
intelliAutoCompleteForm.Hide();
}
private void IntelliAutoCompleteListBox_SelectedIndexChanged(object sender, EventArgs e)
{
if(IsFromMouseClick)
{
if (intelliAutoCompleteListBox.SelectedIndex >= 0)
{
ReplaceCurrentWordWith(intelliAutoCompleteListBox.SelectedItem.ToString());
IsFromReplaceTab = false;
}
}
IsFromMouseClick = false;
}
private void IntelliAutoCompleteListBox_Click(object sender, EventArgs e)
{
IsFromMouseClick = true;
}
private void RichTextBoxIntellisense_SelectionChanged(object sender, EventArgs e)
{
intelliAutoCompleteForm.Hide();
IsNotificationFormShowing = false;
}
private void RichTextBoxIntellisense_KeyPress(object sender, KeyPressEventArgs e)
{
if (IsFromReplaceTab)
{
e.Handled = true;
IsFromReplaceTab = false;
}
else
{
if(e.KeyChar == (char)Keys.Escape)
{
intelliAutoCompleteForm.Hide();
IsNotificationFormShowing = false;
e.Handled = true;
}
}
}
private void RichTextBoxIntellisense_KeyDown(object sender, KeyEventArgs e)
{
if (IsNotificationFormShowing)
{
if (e.KeyCode == Keys.Up)
{
if(intelliAutoCompleteListBox.Items.Count > 0)
{
if(intelliAutoCompleteListBox.SelectedIndex < 0)
{
intelliAutoCompleteListBox.SelectedIndex = 0;
}
else if(intelliAutoCompleteListBox.SelectedIndex > 0)
{
intelliAutoCompleteListBox.SelectedIndex = intelliAutoCompleteListBox.SelectedIndex - 1;
}
}
e.Handled = true;
}
else if (e.KeyCode == Keys.Down)
{
if (intelliAutoCompleteListBox.Items.Count > 0)
{
if (intelliAutoCompleteListBox.SelectedIndex < 0)
{
intelliAutoCompleteListBox.SelectedIndex = 0;
}
else if (intelliAutoCompleteListBox.SelectedIndex < intelliAutoCompleteListBox.Items.Count - 1)
{
intelliAutoCompleteListBox.SelectedIndex = intelliAutoCompleteListBox.SelectedIndex + 1;
}
}
e.Handled = true;
}
else if (e.KeyCode == Keys.Enter)
{
if(intelliAutoCompleteListBox.SelectedIndex >= 0)
{
ReplaceCurrentWordWith(intelliAutoCompleteListBox.SelectedItem.ToString());
}
e.Handled = true;
}
else if (e.KeyCode == Keys.Tab)
{
if (intelliAutoCompleteListBox.SelectedIndex >= 0)
{
ReplaceCurrentWordWith(intelliAutoCompleteListBox.SelectedItem.ToString());
}
e.Handled = true;
}
}
}
private void RichTextBoxIntellisense_TextChanged(object sender, EventArgs e)
{
if (IntellisenseWords != null && IntellisenseWords.Length > 0)
{
string wordText;
int lastIndexOfSpace;
int lastIndexOfNewline;
int lastIndexOfTab;
int lastIndexOf;
if(this.SelectionStart == this.Text.Length)
{
if(this.SelectionStart > 0 && this.Text[this.SelectionStart - 1] != ' ' && this.Text[this.SelectionStart - 1] != '\t' && this.Text[this.SelectionStart - 1] != '\n')
{
wordText = this.Text.Substring(0,this.SelectionStart);
lastIndexOfSpace = wordText.LastIndexOf(' ');
lastIndexOfNewline = wordText.LastIndexOf('\n');
lastIndexOfTab = wordText.LastIndexOf('\t');
lastIndexOf = Math.Max(Math.Max(lastIndexOfSpace,lastIndexOfNewline),lastIndexOfTab);
if (lastIndexOf >= 0)
{
wordText = wordText.Substring(lastIndexOf + 1);
}
if (PopulateIntelliListBox(wordText))
{
ShowAutoCompleteForm();
}
else
{
intelliAutoCompleteForm.Hide();
IsNotificationFormShowing = false;
}
}
else
{
intelliAutoCompleteForm.Hide();
IsNotificationFormShowing = false;
}
}
else
{
char currentChar = this.Text[this.SelectionStart];
if(this.SelectionStart > 0)
{
if(this.SelectionStart > 0 && this.Text[this.SelectionStart - 1] != ' ' && this.Text[this.SelectionStart - 1] != '\t' && this.Text[this.SelectionStart - 1] != '\n'
&& (this.Text[this.SelectionStart] == ' ' || this.Text[this.SelectionStart] == '\t' || this.Text[this.SelectionStart] == '\n'))
{
wordText = this.Text.Substring(0, this.SelectionStart);
lastIndexOfSpace = wordText.LastIndexOf(' ');
lastIndexOfNewline = wordText.LastIndexOf('\n');
lastIndexOfTab = wordText.LastIndexOf('\t');
lastIndexOf = Math.Max(Math.Max(lastIndexOfSpace, lastIndexOfNewline), lastIndexOfTab);
if (lastIndexOf >= 0)
{
wordText = wordText.Substring(lastIndexOf + 1);
}
if(PopulateIntelliListBox(wordText))
{
ShowAutoCompleteForm();
}
else
{
intelliAutoCompleteForm.Hide();
IsNotificationFormShowing = false;
}
}
else
{
intelliAutoCompleteForm.Hide();
IsNotificationFormShowing = false;
}
}
else
{
intelliAutoCompleteForm.Hide();
IsNotificationFormShowing = false;
}
}
}
else
{
intelliAutoCompleteForm.Hide();
IsNotificationFormShowing = false;
}
}
private bool PopulateIntelliListBox(string wordTyping)
{
intelliAutoCompleteListBox.Items.Clear();
List<KeyValuePair<int, string>> tempWords = new List<KeyValuePair<int, string>>();
string[] outArray;
for(int i = 0; i < IntellisenseWords.Length; i++)
{
if(IntellisenseWords[i].StartsWith(wordTyping, StringComparison.CurrentCultureIgnoreCase))
{
tempWords.Add(new KeyValuePair<int, string>(1, IntellisenseWords[i]));
}
}
if(tempWords.Count < _suggestionCount && wordTyping.Length > 1)
{
for (int i = 0; i < IntellisenseWords.Length; i++)
{
if (IntellisenseWords[i].Contains(wordTyping, StringComparison.CurrentCultureIgnoreCase))
{
if(tempWords.Count(c => c.Value == IntellisenseWords[i]) == 0)
{
tempWords.Add(new KeyValuePair<int, string>(2, IntellisenseWords[i]));
}
}
}
}
outArray = tempWords.OrderBy(o => o.Key).Take(_suggestionCount).Select(s => s.Value).ToArray();
intelliAutoCompleteListBox.Items.AddRange(outArray);
return outArray.Length > 0;
}
private void ShowAutoCompleteForm()
{
Point tmpPoint = this.PointToClient(this.Location);
Point tmpSelPoint = this.GetPositionFromCharIndex(this.SelectionStart);
intelliAutoCompleteForm.Location = new Point((-1 * tmpPoint.X) + tmpSelPoint.X + this.XOffset, (-1 * tmpPoint.Y) + tmpSelPoint.Y + this.Margin.Top + this.YOffset);
intelliAutoCompleteForm.Show();
IsNotificationFormShowing = true;
this.Focus();
}
private void ReplaceCurrentWordWith(string Word)
{
string startString = "";
string endString = this.Text.Substring(this.SelectionStart);
string wordText = this.Text.Substring(0, this.SelectionStart);
int lastIndexOfSpace = wordText.LastIndexOf(' ');
int lastIndexOfNewline = wordText.LastIndexOf('\n');
int lastIndexOfTab = wordText.LastIndexOf('\t');
int lastIndexOf = Math.Max(Math.Max(lastIndexOfSpace, lastIndexOfNewline), lastIndexOfTab);
if (lastIndexOf >= 0)
{
startString = wordText.Substring(0, lastIndexOf + 1);
wordText = wordText.Substring(lastIndexOf + 1);
}
this.Text = String.Format("{0}{1} {2}", startString, Word, endString);
if(lastIndexOf >= 0)
{
this.SelectionStart = startString.Length + Word.Length + 1;
}
else
{
this.SelectionStart = Word.Length + 1;
}
IsFromReplaceTab = true;
}
}
I'm really new to programming. C# is the first class I've taken and I'm stuck on this a project. We had to create a program that will calculate the cost of workshop after selecting a workshop radiobutton and a location radio button. I've got everything working the way it's supposed to except for one thing.
Let's say you select a workshop, but you don't select a location. I have it to where a MessageBox will show up saying to "select a location," but how do I stop the program from calculating if this happens? As of now, it will just calculate and give the location amount 0. I need it to not calculate at all.
public partial class frmWorkshopSelector : Form
{
public frmWorkshopSelector()
{
InitializeComponent();
}
private void btnExit_Click(object sender, EventArgs e)
{
this.Close(); //When clicking the exit button, the program will close
}
private void btncalc_Click(object sender, EventArgs e)
{
int wsregistration = 0;
int lcost = 0;
const decimal DAYS = 3;
//For the following if statements, depending on what workshop and location is selected,
//their correstponding registration and lodging fees will be displayed
{
if (rbtHandlingStress.Checked == true)
{
wsregistration = 1000;
}
else if (rbtSupervisionSkills.Checked == true)
{
wsregistration = 1500;
}
else if (rbtTimeManagement.Checked == true)
{
wsregistration = 800;
}
else
MessageBox.Show("Please Select a Workshop");
lblTotalCost.Text = "";
lblLodgingCost.Text = "";
lblRegistrationCost.Text = "";
}
{
if (rbtAustin.Checked == true)
{
lcost = 150;
}
else if (rbtChicago.Checked == true)
{
lcost = 225;
}
else if (rbtDallas.Checked == true)
{
lcost = 175;
}
else
{
MessageBox.Show("Please Select a Location");
lblRegistrationCost.Text = " ";
lblTotalCost.Text = " ";
lblLodgingCost.Text = " ";
}
}
lblRegistrationCost.Text = wsregistration.ToString("C");
lblLodgingCost.Text = lcost.ToString("C");
lblTotalCost.Text = (wsregistration + (lcost * DAYS)).ToString("C");
}
private void btnReset_Click(object sender, EventArgs e)
{
//unchecks all radio buttons as well as clears out the previous calculations
lblRegistrationCost.Text = "";
lblLodgingCost.Text = "";
lblTotalCost.Text = "";
rbtHandlingStress.Checked = false;
rbtSupervisionSkills.Checked = false;
rbtTimeManagement.Checked = false;
rbtAustin.Checked = false;
rbtChicago.Checked = false;
rbtDallas.Checked = false;
}
}
You have to exit from the method. Added return statement in else block.
private void btncalc_Click(object sender, EventArgs e)
{
int wsregistration = 0;
int lcost = 0;
const decimal DAYS = 3;
//For the following if statements, depending on what workshop and location is selected,
//their correstponding registration and lodging fees will be displayed
if (rbtHandlingStress.Checked == true)
{
wsregistration = 1000;
}
else if (rbtSupervisionSkills.Checked == true)
{
wsregistration = 1500;
}
else if (rbtTimeManagement.Checked == true)
{
wsregistration = 800;
}
else
{
lblTotalCost.Text = "";
lblLodgingCost.Text = "";
lblRegistrationCost.Text = "";
MessageBox.Show("Please Select a Workshop");
return;
}
if (rbtAustin.Checked == true)
{
lcost = 150;
}
else if (rbtChicago.Checked == true)
{
lcost = 225;
}
else if (rbtDallas.Checked == true)
{
lcost = 175;
}
else
{
lblRegistrationCost.Text = " ";
lblTotalCost.Text = " ";
lblLodgingCost.Text = " ";
MessageBox.Show("Please Select a Location");
return;
}
lblRegistrationCost.Text = wsregistration.ToString("C");
lblLodgingCost.Text = lcost.ToString("C");
lblTotalCost.Text = (wsregistration + (lcost * DAYS)).ToString("C");
}
writing a "return" anywhere within the function exits that function, maybe after you show the message box to enter location, you type
return;
and this should do the job.
Just Add return statement in your code after showing the message box like below
public partial class frmWorkshopSelector : Form
{
public frmWorkshopSelector()
{
InitializeComponent();
}
private void btnExit_Click(object sender, EventArgs e)
{
this.Close(); //When clicking the exit button, the program will close
}
private void btncalc_Click(object sender, EventArgs e)
{
int wsregistration = 0;
int lcost = 0;
const decimal DAYS = 3;
//For the following if statements, depending on what workshop and location is selected,
//their correstponding registration and lodging fees will be displayed
{
if (rbtHandlingStress.Checked == true)
{
wsregistration = 1000;
}
else if (rbtSupervisionSkills.Checked == true)
{
wsregistration = 1500;
}
else if (rbtTimeManagement.Checked == true)
{
wsregistration = 800;
}
else
MessageBox.Show("Please Select a Workshop");
lblTotalCost.Text = "";
lblLodgingCost.Text = "";
lblRegistrationCost.Text = "";
return;
}
{
if (rbtAustin.Checked == true)
{
lcost = 150;
}
else if (rbtChicago.Checked == true)
{
lcost = 225;
}
else if (rbtDallas.Checked == true)
{
lcost = 175;
}
else
{
MessageBox.Show("Please Select a Location");
lblRegistrationCost.Text = " ";
lblTotalCost.Text = " ";
lblLodgingCost.Text = " ";
return;
}
}
lblRegistrationCost.Text = wsregistration.ToString("C");
lblLodgingCost.Text = lcost.ToString("C");
lblTotalCost.Text = (wsregistration + (lcost * DAYS)).ToString("C");
}
private void btnReset_Click(object sender, EventArgs e)
{ //uncheks all radio buttons as well as clears out the previous calculations
lblRegistrationCost.Text = "";
lblLodgingCost.Text = "";
lblTotalCost.Text = "";
rbtHandlingStress.Checked = false;
rbtSupervisionSkills.Checked = false;
rbtTimeManagement.Checked = false;
rbtAustin.Checked = false;
rbtChicago.Checked = false;
rbtDallas.Checked = false;
}
}
}
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