How to find label controls in an asp.net page - c#

I have some label controls in a panel with id ResultsPanel. To find the label controls on the page, I did the following:
for (int ctr = 0; ctr < lblString.Length - 1; ctr++)
{
//string labelID = string.Format("lblResult{0}", ctr);
int mylbl = ctr + 1;
string lblResult = ((Label)ResultsPanel.FindControl("lblResult" + mylbl.ToString())).Text;
lblResult = lblString[mylbl].ToString();
}
lblResult1.Text = lblString.ToString();
lblString is a stringBuilder Object with 24 numbers. The Idea is to map each of the numbers in the stringbuilder object to labels in this manner:
lblResult1.Text = lblString[mylbl].ToString(); to the 24th label. But I can't seem to generate the labels and map the values to the label control.

Change the line to
Label lblResult = ((Label)ResultsPanel.FindControl("lblResult" + mylbl.ToString()));
lblResult.Text = lblString[mylbl].ToString();

Your question and code are a bit misleading, but I will try my best anyway.
Your code:
for (int ctr = 0; ctr < lblString.Length - 1; ctr++)
{
//string labelID = string.Format("lblResult{0}", ctr);
int mylbl = ctr + 1;
string lblResult = ((Label)ResultsPanel.FindControl("lblResult" + mylbl.ToString())).Text;
lblResult = lblString[mylbl].ToString();
}
lblResult1.Text = lblString.ToString();
If you have labels in the order of label1, label2, label3 ... then I would write something like this:
private void MapLabels()
{
var labelsResult = string.Empty;
var labelString = "123456789";
for (int i = 0; i < labelString.Length; i++)
{
var control = this.FindControl("label" + labelString[i]);
if(control != null)
{
labelsResult += ((Label)control).Text;
}
}
labelResult1.Text = labelsResult;
}
Let me know if you get stuck.

Hope this will help you. Like this you can get the value of label too.
public void GetControlsValuePopulated(Control control, Type controlType, Dictionary<string, string> dictControlPageValParam)
{
try
{
if (control.HasControls())
{
GetControlsValuePopulated(control, controlType, dictControlPageValParam);
}
else
{
if (controlType == null || controlType.IsAssignableFrom(control.GetType()))
{
if (control.ID != null)
{
bool FoundControl = dictControlPageValParam.ContainsKey(control.ID.Substring(3));
if (FoundControl)
{
switch (control.GetType().ToString())
{
case "System.Web.UI.WebControls.TextBox":
TextBox txt = (TextBox)control;
txt.Text = dictControlPageValParam[txt.ID.Substring(3)];
break;
case "System.Web.UI.WebControls.CheckBox":
CheckBox chk = (CheckBox)control;
if (dictControlPageValParam[chk.ID.Substring(3)].ToUpper() == "TRUE" || dictControlPageValParam[chk.ID.Substring(3)].ToUpper() == "T")
{
chk.Checked = true;
}
else
{
chk.Checked = false;
}
break;
case "System.Web.UI.WebControls.DropDownList":
DropDownList ddl = (DropDownList)control;
//ddl.SelectedValue = dictControlPageValParam[ddl.ID.Substring(3)];
break;
case "System.Web.UI.WebControls.RadioButtonList":
RadioButtonList rbl = (RadioButtonList)control;
rbl.SelectedValue = dictControlPageValParam[rbl.ID.Substring(3)];
break;
case "System.Web.UI.WebControls.HiddenField":
HiddenField hdn = (HiddenField)control;
hdn.Value = dictControlPageValParam[hdn.ID.Substring(3)];
break;
}
}
}
}
}
}
catch (Exception)
{
throw;
}
}
public void GetChildControlsId(Control control, Type controlType)
{
try
{
if (control.HasControls())
{
GetChildControlsId(control, controlType);
}
else
{
if (controlType == null || controlType.IsAssignableFrom(control.GetType()))
{
///checking if control already existing in the collection
if (control.ID != null)
{
bool FoundControl = controlHt.ContainsKey(control.ID);
if (!FoundControl)
{
switch (control.GetType().ToString())
{
case "System.Web.UI.WebControls.TextBox":
TextBox txt = (TextBox)control;
controlTypeName = txt.ID;
controlTypeName = controlTypeName.Substring(3);
controlTypeValue = txt.Text;
if (dictControlValParam.ContainsKey(controlTypeName) == false)
{
dictControlValParam.Add(controlTypeName, controlTypeValue);
}
else
{
dictControlValParam.Remove(controlTypeName);
dictControlValParam.Add(controlTypeName, controlTypeValue);
}
break;
case "System.Web.UI.WebControls.CheckBox":
CheckBox chk = (CheckBox)control;
controlTypeName = chk.ID;
controlTypeName = controlTypeName.Substring(3);
controlTypeValue = chk.Checked.ToString();
if (dictControlValParam.ContainsKey(controlTypeName) == false)
{
dictControlValParam.Add(controlTypeName, controlTypeValue);
}
else
{
dictControlValParam.Remove(controlTypeName);
dictControlValParam.Add(controlTypeName, controlTypeValue);
}
break;
case "System.Web.UI.WebControls.DropDownList":
DropDownList ddl = (DropDownList)control;
controlTypeName = ddl.ID;
controlTypeName = controlTypeName.Substring(3);
controlTypeValue = ddl.SelectedValue.ToString();
if (dictControlValParam.ContainsKey(controlTypeName) == false)
{
dictControlValParam.Add(controlTypeName, controlTypeValue);
}
else
{
dictControlValParam.Remove(controlTypeName);
dictControlValParam.Add(controlTypeName, controlTypeValue);
}
break;
case "System.Web.UI.WebControls.RadioButtonList":
RadioButtonList rbl = (RadioButtonList)control;
controlTypeName = rbl.ID;
controlTypeName = controlTypeName.Substring(3);
controlTypeValue = rbl.SelectedValue.ToString();
if (dictControlValParam.ContainsKey(controlTypeName) == false)
{
dictControlValParam.Add(controlTypeName, controlTypeValue);
}
else
{
dictControlValParam.Remove(controlTypeName);
dictControlValParam.Add(controlTypeName, controlTypeValue);
}
break;
case "System.Web.UI.WebControls.HiddenField":
HiddenField hdn = (HiddenField)control;
controlTypeName = hdn.ID;
controlTypeName = controlTypeName.Substring(3);
controlTypeValue = hdn.Value;
if (dictControlValParam.ContainsKey(controlTypeName) == false)
{
dictControlValParam.Add(controlTypeName, controlTypeValue);
}
else
{
dictControlValParam.Remove(controlTypeName);
dictControlValParam.Add(controlTypeName, controlTypeValue);
}
break;
}
}
}
}
}
}
catch (Exception)
{
throw;
}
}

Related

add listview item from another form

I treid to add item to listview from another form
its the method in form1 (one the listview located)
private void AfterAdd_DoWork(object sender, DoWorkEventArgs e)
{
int[] sizes = SellBL.Product.GetProdStockByID(prodid);
ListViewItem Item = new ListViewItem(prodid.ToString());
Item.SubItems.Add(prodname);
Item.SubItems.Add(ebayid);
Item.SubItems.Add("$" + sellprice);
if (!isnosize)
{
for (int i = 0; i < sizes.Length; ++i)
{
if (sizes[i] == 1)
{
Item.UseItemStyleForSubItems = false;
var subItem = Item.SubItems.Add("In Stock");
subItem.ForeColor = Color.Green;
}
else if (sizes[i] == 0)
{
Item.UseItemStyleForSubItems = false;
var subItem = Item.SubItems.Add("Out Of Stock");
subItem.ForeColor = Color.Red;
}
else if (sizes[i] == 2)
{
Item.UseItemStyleForSubItems = false;
var subItem = Item.SubItems.Add("Less Than 3");
subItem.ForeColor = Color.Orange;
}
else if (sizes[i] == 5)
{
Item.UseItemStyleForSubItems = false;
var subItem = Item.SubItems.Add("Less Than 5");
subItem.ForeColor = Color.Orange;
}
else if (sizes[i] == 10)
{
Item.UseItemStyleForSubItems = false;
var subItem = Item.SubItems.Add("Less Than 10");
subItem.ForeColor = Color.Orange;
}
}
}
else
{
if (sizes[0] == 1)
{
Item.UseItemStyleForSubItems = false;
var subItem = Item.SubItems.Add("In Stock");
subItem.ForeColor = Color.Green;
}
else if (sizes[0] == 0)
{
Item.UseItemStyleForSubItems = false;
var subItem = Item.SubItems.Add("Out Of Stock");
subItem.ForeColor = Color.Red;
}
else if (sizes[0] == 10)
{
Item.UseItemStyleForSubItems = false;
var subItem = Item.SubItems.Add("Few Left");
subItem.ForeColor = Color.Orange;
}
}
ProductListView.Invoke(new MethodInvoker(delegate () { ProductListView.Items.AddRange(new ListViewItem[] { Item }); }));
}
and it the form2 (from there I wont to add the product)
private void backgroundWorkerAddProd_DoWork(object sender, DoWorkEventArgs e)
{
string a = Addprodnametxt.Text.ToString();
string b = Addprodebayidtxt.Text.ToString();
string c = addprodsellpricetxt.Text.ToString();
f1.AfterProductAdded(1, a, b, c, false);
}
I tried the method: ProductListView.items.add(item);
but it doesnt work
and when I tried this method: ProductListView.Invoke(new MethodInvoker(delegate () { ProductListView.Items.AddRange(new ListViewItem[] { Item }); }));
I got this error:
System.InvalidOperationException: 'Invoke or BeginInvoke cannot be called on a control until the window handle has been created.'
how can I fix it?
thanks
try this
if (System.Windows.Forms.Application.OpenForms["yourForm"] != null)
{
(System.Windows.Forms.Application.OpenForms["yourForm"] as Form1).AfterAdd_DoWork();
}

Customize TextBox autocomplete

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

How to shorten if-else-if statement in c#

Can someone shorten this code?
There are 14 Buttons and 8 text Boxes. The action will be perform if the textbox is not empty and if it is not empty, then when you click it the button corresponding with the letter in the textbox will be visible again making the textbox empty.
private void txt1_Click(object sender, EventArgs e)
{
if (txt1.Text == "J")
{
txt1.Text = "";
btn1.Visible = true;
}
else if (txt1.Text == "M")
{
txt1.Text = "";
btn2.Visible = true;
}
else if (txt1.Text == "Y")
{
txt1.Text = "";
btn3.Visible = true;
}
else if (txt1.Text == "E")
{
if (btn4.Visible == true)
{
txt1.Text = "";
btn5.Visible = true;
}
else
{
txt1.Text = "";
btn4.Visible = true;
}
}
else if (txt1.Text == "Q")
{
txt1.Text = "";
btn6.Visible = true;
}
else if (txt1.Text == "L")
{
if (btn7.Visible == true)
{
txt1.Text = "";
btn10.Visible = true;
}
else
{
txt1.Text = "";
btn7.Visible = true;
}
}
else if (txt1.Text == "B")
{
txt1.Text = "";
btn8.Visible = true;
}
else if (txt1.Text == "C")
{
txt1.Text = "";
btn9.Visible = true;
}
else if (txt1.Text == "P")
{
txt1.Text = "";
btn11.Visible = true;
}
else if (txt1.Text == "I")
{
txt1.Text = "";
btn12.Visible = true;
}
else if (txt1.Text == "K")
{
txt1.Text = "";
btn13.Visible = true;
}
else if (txt1.Text == "O")
{
txt1.Text = "";
btn14.Visible = true;
}
}
Assuming all the btn variables are part of the state of your class then you can declare a method like so:
public Button Click(String txt) {
switch(txt) {
case "J":
return btn1;
case "M":
return btn2;
case "Y":
return btn3;
case "E":
return (btn4.Visible ? btn5 : btn4);
case "Q":
return btn6;
case "L":
return (btn7.Visible ? btn10 : btn7);
case "B":
return btn8;
case "C":
return btn9;
case "P":
return btn11;
case "I":
return btn12;
case "K":
return btn13;
case "O":
return btn14;
}
return null;
}
and then you call it:
var button = Click(txt1.Text);
if(button != null) {
button.Visible = true;
txt1.Text = "";
}
If however the btn variables have local scope, than instead of a method you can just define an inline Func<String,Button> delegate as so:
Func<String, Button> Click = txt => {
switch(txt) {
...
}
};
You'd still have to handle the special cases ("E" and "L") but you could use a Dictionary<string, Button> which would allow you to do a lookup:
var buttonDictionary = new Dictionary<string, Button>();
buttonDictionary["J"] = btn1;
buttonDictionary["M"] = btn2;
//etc...
if (buttonDictionary.Keys.Contains(txt1.Text))
{
txt1.Text = "";
buttonDictionary[txt1.Text].Visible = false;
}
That would reduce most of the repetitive code.
Looking at this: I'd suggest you go back think of more logical way to do whatever you're doing.
Out of my experience, any enormous chains of if-else in code represent that there has been a logical issue somewhere.
Also, familiarize yourself with switch statements

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

Searching for a tabpage in the tabcontrol C#

I have a tabcontrol in my application. I have a listbox which contains the line no of error and file name and path of the file.On double click i want to add the new tab page.The title of the tabpage should be the name of file from the listbox. If the tabpage with the particular filename already exists then it should not open new tabpage the cursor should point to that page. How to retreive the name of the tabpages .
private void lstErrorList_MouseDoubleClick(object sender, MouseEventArgs e)
{
ArrayList errorType = new ArrayList();
if (lstErrorList.Items.Count > 0)
{
string error = lstErrorList.SelectedItem.ToString();
{
int result = error.LastIndexOf('\\');
string filename = error.Substring(result + 1, error.Length - (result + 1));
int pagecount;
TabPage tp = new TabPage();
pagecount = this.tabControl1.TabPages.Count;
for(int tbpagecount=0;tbpagecount<pagecount;tbpagecount++)
{
pagelist.Add(this.tabControl1.TabPages.ToString());
}
if (pagelist.Contains(filename))
{
}
else
{
this.tabControl1.TabPages.Insert(pagecount, filename);
pagecount++;
}
if (fileNamesList.Count == 0)
fileNamesList.Add(filename);
else
{
if (fileNamesList.Contains(filename))
{
//fileNamesList.Add("");
}
else
{
fileNamesList.Add(filename);
}
}
}
bool found = false;
foreach (TabPage tab in tabControl1.TabPages) {
if (filename.Equals(tab.Name)) {
tabControl1.SelectedTab = tab;
found = true;
}
}
if( ! found)
tabControl1.TabPages.Add(filename,filename);
var tabPage = tabControl1.TabPages[filename];
if (tabPage != null)
{
tabControl1.SelectedTab = tabPage;
}
else
{
tabControl1.TabPages.Add(filename, filename);
}
What about something like this?
string fileName = "";
bool isPresent = false;
for (int i = 0; i < tabControl1.TabPages.Count; i++)
{
if (tabControl1.TabPages[i].Name == filename)
{
isPresent = true;
break;
}
}
if (isPresent)
{
tabControl1.TabPages.Add(filename);
}
else
{
tabControl1.SelectTab(tab.TabIndex);
}

Categories

Resources