Dynamic Controls not Displaying - placeholder

I am creating controls on some input XML.
The controls are then added to the different PlaceHolder Control which is places in a table. Here is the code for reference
private void RenderFactorControls(string xml)
{
XmlDocument xmlDoc = new XmlDocument();
xmlDoc.LoadXml(xml);
foreach (XmlNode xmlNode in xmlDoc.DocumentElement.ChildNodes)
{
CheckBox factorCheckBox = new CheckBox();
factorCheckBox.ID = "chkBox"+xmlNode.Attributes["id"].Value;
factorCheckBox.Text = xmlNode.Attributes["id"].Value;
this.pholderControls1.Controls.Add(factorCheckBox);
this.pholderControls2.Controls.Add(factorCheckBox);
this.pholderControls3.Controls.Add(factorCheckBox);
this.pholderControls4.Controls.Add(factorCheckBox);
this.pholderControls5.Controls.Add(factorCheckBox);
}
}
Only the last place holder shows the controls.

private void RenderFactorControls(string xml)
{
XmlDocument xmlDoc = new XmlDocument();
xmlDoc.LoadXml(xml);
foreach (XmlNode xmlNode in xmlDoc.DocumentElement.ChildNodes)
{
string id = "chkBox"+xmlNode.Attributes["id"].Value;
string text = xmlNode.Attributes["id"].Value;
this.pholderControls1.Controls.Add(new CheckBox() { ID = id, Text = text });
this.pholderControls2.Controls.Add(new CheckBox() { ID = id, Text = text });
this.pholderControls3.Controls.Add(new CheckBox() { ID = id, Text = text });
this.pholderControls4.Controls.Add(new CheckBox() { ID = id, Text = text });
this.pholderControls5.Controls.Add(new CheckBox() { ID = id, Text = text });
}
}

You created only One CheckBox and are trying to add it to multiple placeholders. Adding a control to a container removes it from its previous parent. Try creating 5 different checkboxes.

Related

Populate labels when selecting item in listbox

I have a listbox that contains the first index of every line in a text file.
the indexes are seperated with a ','.
I would like to select an item in the listbox and have it populate the labels I have in place with the rest of the line from the text file.
private void listsup_MouseClick(object sender, MouseEventArgs e)
{
Supfile = System.AppDomain.CurrentDomain.BaseDirectory + "data\\Suppliers.txt";
StreamReader spl = new StreamReader(Supfile);
string word = Convert.ToString(listsup.SelectedItem);
List<string> values = new List<string>();
foreach (string str in values)
{
if (str.Contains(word))
{
string[] tokens = str.Split(',');
labelsupnm.Text = tokens[0];
labelconpers.Text = tokens[1];
labeldiscr1.Text = tokens[2];
labeldiscr2.Text = tokens[3];
labeldiscr3.Text = tokens[4];
labeldiscr4.Text = tokens[5];
labeldiscr5.Text = tokens[6];
}
}
}
Problem is, I'm not getting anything to display in my labels, please help.
I changed my code a little, added some code that I used to populate the listbox itself, and now it all works just fine.
private void listsup_MouseClick(object sender, MouseEventArgs e)
{
Supfile = System.AppDomain.CurrentDomain.BaseDirectory + "data\\Suppliers.txt";
try
{
StreamReader supFile;
supFile = File.OpenText(Supfile);
string lines;
while (!supFile.EndOfStream)
{
lines = supFile.ReadLine();
string[] tokens = lines.Split(',');
string tr = listsup.SelectedItem.ToString();
if (tr.Equals(tokens[0]))
{
labelsupnm.Text = tokens[0];
labelconpers.Text = tokens[1];
labeldiscr1.Text = tokens[2];
labeldiscr2.Text = tokens[3];
labeldiscr3.Text = tokens[4];
labeldiscr4.Text = tokens[5];
labeldiscr5.Text = tokens[6];
}
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}

Xamarin Android, get contact mobile number by using CursorLoader with selection and selection args

I'm trying to get contact details of a contact that the user picks from the contacts list in Android using Intent as the following code:
Intent Intent = new Intent(Intent.ActionPick, ContactsContract.Contacts.ContentUri);
Intent.SetType(ContactsContract.Contacts.ContentType);
StartActivityForResult(Intent, 3);
Now on the Intent results I run the following code to get specific contact information:
public override void OnActivityResult(int requestCode, int resultCode, Intent data)
{
if (requestCode == 3 && resultCode == -1 && data != null) //result code -1 means OK 0 Means cancelled Result.Ok
{
var ContactData = data.Data;
string ID = "";
string name = "";
string address = "";
byte[] picture = new byte[0];
List<string> numbers = new List<string>();
List<string> emails = new List<string>();
string mobile = "";
string email = "";
string selectionString = "id = ?";
string[] columnsNames = new string[] {
ContactsContract.Contacts.InterfaceConsts.Id,
ContactsContract.Contacts.InterfaceConsts.DisplayName,
ContactsContract.Contacts.InterfaceConsts.PhotoUri
};
var loader = new CursorLoader(Statics.mainActivity, ContactData, null, null, null, null);
var cursor = (ICursor)loader.LoadInBackground();
if (cursor.MoveToFirst())
{
ID = cursor.GetString(cursor.GetColumnIndex(columnsNames[0]));
name = cursor.GetString(cursor.GetColumnIndex(columnsNames[1]));
picture = cursor.GetBlob(cursor.GetColumnIndex(columnsNames[2]));
}
//Store Contact ID
string[] selectionStringArgs = new string[] { ID };
//Phone Numbers
string[] columnsNames2 = new string[] {
ContactsContract.CommonDataKinds.Phone.Number
};
var loader2 = new CursorLoader(Statics.mainActivity, ContactsContract.CommonDataKinds.Phone.ContentUri, columnsNames2, selectionString, selectionStringArgs, null);
var cursor2 = (ICursor)loader2.LoadInBackground();
while (cursor2.MoveToNext())
{
numbers.Add(cursor2.GetString(cursor2.GetColumnIndex(columnsNames2[0])));
}
//Email Address
string[] columnsNames3 = new string[] {
ContactsContract.CommonDataKinds.Email.Address
};
var loader3 = new CursorLoader(Statics.mainActivity, ContactsContract.CommonDataKinds.Email.ContentUri, columnsNames3, selectionString, selectionStringArgs, null);
var cursor3 = (ICursor)loader3.LoadInBackground();
while (cursor3.MoveToNext())
{
emails.Add(cursor3.GetString(cursor3.GetColumnIndex(columnsNames3[0])));
}
int TempRecepitntID = 0;
EmployeesViewModel tempRecipent = new EmployeesViewModel();
TempRecepitntID = Statics.mainActivity.currentViewModel.SelectedChat.ReceiverEmployee;
foreach (EmployeesViewModel evm in Statics.mainActivity.currentViewModel.Employees)
{
if (evm.ID == TempRecepitntID)
tempRecipent = evm;
}
new Android.Support.V7.App.AlertDialog.Builder(Statics.mainActivity)
.SetPositiveButton("Yes", (sender1, args) =>
{
Statics.mainActivity.currentViewModel.AddMessage(picture, tempRecipent, Statics.mainActivity.currentViewModel.SelectedChat.ID, "contact", 0, "", name, numbers[0], mobile, email, address);
})
.SetNegativeButton("No", (sender1, args) =>
{
// cancel
})
.SetMessage("Are you shure you want to send?")
.SetTitle("System Message")
.Show();
}
}
The problem is I want to retrieve only the information of the contact that the user selected but what I get is all other contacts data is retrieved so I tried to use the selection and selectionargs parameters of CursorLoader by setting string selectionString = "id = ?"; and selectionArgs to string[] selectionStringArgs = new string[] { ID }; the ID value is retrieved from the following code :
if (cursor.MoveToFirst())
{
ID = cursor.GetString(cursor.GetColumnIndex(columnsNames[0]));
name = cursor.GetString(cursor.GetColumnIndex(columnsNames[1]));
picture = cursor.GetBlob(cursor.GetColumnIndex(columnsNames[2]));
}
//Store Contact ID
string[] selectionStringArgs = new string[] { ID };
//Phone Numbers
string[] columnsNames2 = new string[] {
ContactsContract.CommonDataKinds.Phone.Number
};
But now it returns 0 results, I couldn't find anything on the internet that applies to Xamarin android, Please help.
Thanks,
Finally I found the solution, I used the following string in the selection parameter of the cursorloader method:
string selectionString = ContactsContract.CommonDataKinds.Phone.InterfaceConsts.ContactId + "=" + ID;
and now only the selected contact numbers are retrieved.
I hope this will help someone else.
In additional information of #TMSL, I add the code afer this bloque
if (cursor.MoveToFirst())
{
ID = cursor.GetString(cursor.GetColumnIndex(columnsNames[0]));
name = cursor.GetString(cursor.GetColumnIndex(columnsNames[1]));
picture = cursor.GetBlob(cursor.GetColumnIndex(columnsNames[2]));
}
Here
selectionString = ContactsContract.CommonDataKinds.Phone.InterfaceConsts.ContactId + "=" + ID;
Then I changed the parameters used in the definition of variable Loader2, converting selectionStringArgs in null.
var loader2 = new CursorLoader(this.Activity, ContactsContract.CommonDataKinds.Phone.ContentUri, columnsNames2, selectionString, null,null);
var cursor2 = (ICursor)loader2.LoadInBackground();
I found this documentation from xamarin guides
Uri – The fully qualified name of the ContentProvider.
Projection – Specification of which columns to select for the cursor.
Selection – Similar to a SQL WHERE clause.
SelectionArgs – Parameters to be substituted in the Selection.
SortOrder – Columns to sort by.
So, the variable selectionStringArgs used in the code from #TMSAL cannot use a value like "contact_id = 2700", because the parameter of CursorLoader SelectionArgs is not a filter but not "Parameters to be substituted in the Selection"
I hope this will help someone else too.

What kind of object has to be passed for JsonResult in MVC.Net

So I'm passing a custom class to my controller and it seems that the JsonResult is not properly passed.
What bothers me is that (also the fullcalendar wont read the json) the console.log which I have in my view prints the path to the function (wtf?) instead of what Json shoul return
This is my code:
public JsonResult GetCalendarEvents()
{
var eventList = BusinessLayer.Event.getAllEvents();
return Json(eventList.ToArray(), JsonRequestBehavior.AllowGet);
}
What kind of object has to be passed for this to work?
My evenList is of type List<Event> from here:
public static String ListToString(List<Event> evs)
{
String ret = "";
foreach (var ev in evs)
{
ret += ev.ToString() + "\n";
}
return ret;
}
public static List<Event> getAllEvents()
{
List<DataLayer.Event> dbEvents = DataApi.db.Event.ToList();
List<Event> returnEvents = new List<Event>();
foreach (DataLayer.Event oneEvent in dbEvents)
{
Event newEvent = new Event
{
ID = oneEvent.IDEvent,
userID = oneEvent.UserID,
projectID = oneEvent.ProjectID,
jobtypeID = oneEvent.JobTypeID,
taskID = oneEvent.TaskID,
ticketID = oneEvent.TicketID,
loccoID = oneEvent.LoccoID,
startTime = oneEvent.StartTime,
endTime = oneEvent.EndTime,
shiftFrom = oneEvent.ShiftFrom,
shiftTo = oneEvent.ShiftTo,
description = oneEvent.Description,
billable = oneEvent.Billable
};
returnEvents.Add(newEvent);
}
return returnEvents;
}
I tried displaying the events in fullcalendar:
$('#calendar').fullCalendar({
header: {
left: 'title',
center: '',
right: 'prev,next today basicDay,basicWeek,month',
},
//events: "/Calendar/GetEvents/", // not implemented
events: "#Url.Action("GetCalendarEvents/")",
and outputing the result to console:
console.log("#Url.Action("GetCalendarEvents/")");
but I get:
VM84 Index:83 /Calendar/GetCalendarEvents/
fullcalendar.min.js:6 Uncaught TypeError: Cannot read property 'hasTime' of undefined
It looks like you're missing some required fields. If you look at the documentation, title, start are required. Try setting these in the class to start with and build from that...
public static List<Event> getAllEvents()
{
List<DataLayer.Event> dbEvents = DataApi.db.Event.ToList();
List<Event> returnEvents = new List<Event>();
foreach (DataLayer.Event oneEvent in dbEvents)
{
Event newEvent = new Event
{
start = oneEvent.StartTime,
title = oneEvent.Description // you may need to add this to your Event class.
};
returnEvents.Add(newEvent);
}
return returnEvents;
}
Also, instead of using console to log the Json, use Fiddler or Chrome Advanced Tools

Add text to bound values in Xamarin.forms

My modelView:
public string Status {
get { return _status; }
set {
if (value == _status) {
return;
}
_status = value;
OnPropertyChanged ("Status");
}
My View:
Label labelStatus = new Label {
TextColor = Color.Green,
FontSize = 20d
};
labelStatus.SetBinding (Label.TextProperty, "Status");
Then I want to present the status using something like:
string presentStatus = string.Format("Your status is {0}...", labelStatus);
Label yourStatus = new Label{Text=presentStatus}
But that doesn't really work. Nor does using
string presentStatus = string.Format("Your status is {0}...", SetBinding(Label.TextProperty,"Status"));
So how should I do to add my bound values with more text before presenting them for the user in a view.
If using XAML (which i don't), it seems possible according to: http://developer.xamarin.com/guides/cross-platform/xamarin-forms/xaml-for-xamarin-forms/data_binding_basics/
Xamarin Forms binding implementation doesn't currently allow complex binding scenarios like embedding bound text within static text.
There are two options
a. use multiple labels - one with the static text, one with the bound text
b. use a property on your ViewModel that concatenates the text for you
public string StatusText
{
get
{
return string.Format("Your status is {0}...", Status);
}
}
public string Status {
get { return _status; }
set {
if (value == _status) {
return;
}
_status = value;
OnPropertyChanged ("Status");
OnPropertyChanged ("StatusText");
}
You can do that in the BindingContextChanged-event:
labelStatus.BindingContextChanged += (sender, e) =>
{
// Here you can change the Text dynamically
// E.G. labelStatus.text = "Title: " + labelStatus.text
};

Monotouch.Dialog Generate from db and retain values

I'm have a settings view where I'm using MT.D to build out my UI. I just got it to read elements from a database to populate the elements in a section.
What I don't know how to do is access each elements properties or values. I want to style the element with a different background color for each item based on it's value in the database. I also want to be able to get the selected value so that I can update it in the db. Here's the rendering of the code that does the UI stuff with MT.D. I can get the values to show up and slide out like their supposed to... but, styling or adding delegates to them to handle clicks I'm lost.
List<StyledStringElement> clientTypes = SettingsController.GetClientTypes ();
public SettingsiPhoneView () : base (new RootElement("Home"), true)
{
Root = new RootElement("Settings") {
new Section ("Types") {
new RootElement ("Types") {
new Section ("Client Types") {
from ct in clientTypes
select (Element) ct
}
},
new StringElement ("Other Types")
}
Here's how I handled it below. Basically you have to create the element in a foreach loop and then populate the delegate with whatever you want to do there. Like so:
public static List<StyledStringElement> GetClientTypesAsElement ()
{
List<ClientType> clientTypes = new List<ClientType> ();
List<StyledStringElement> ctStringElements = new List<StyledStringElement> ();
using (var db = new SQLite.SQLiteConnection(Database.db)) {
var query = db.Table<ClientType> ().Where (ct => ct.IsActive == true && ct.Description != "Default");
foreach (ClientType ct in query)
clientTypes.Add (ct);
}
foreach (ClientType ct in clientTypes) {
// Build RGB values from the hex stored in the db (Hex example : #0E40BF)
UIColor bgColor = UIColor.Clear.FromHexString(ct.Color, 1.0f);
var localRef = ct;
StyledStringElement element = new StyledStringElement(ct.Type, delegate {
ClientTypeView.EditClientTypeView(localRef.Type, localRef.ClientTypeId);
});
element.BackgroundColor = bgColor;
ctStringElements.Add (element);
}
return ctStringElements;
}

Resources