Populate labels when selecting item in listbox - 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);
}
}

Related

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

How to remove partucular list of querystring from current page url querystring in c#2.0

Say my current page url has got (http://mysite/english/faq.aspx?faqid=12123&cid=4545&intcid=65456&h=man)
string excludeQuerystring = DynConfig.Item("GoogleSEOLinkSettings/ExcludeQuerystring"); //this is the list of my exclude querystring (cid,intcid,del)
querystring = HttpContext.Current.Request.Url.AbsoluteUri.Split('?')[1]; //I will get faqid=12123&cid=4545,intcid=65456
StringBuilder fullQueryString = new StringBuilder();
if (!string.IsNullOrEmpty(excludeQuerystring) && !string.IsNullOrEmpty(querystring))
{
string[] strEQ = excludeQuerystring.Split(','); //making a array of excluded querystrings
NameValueCollection navValues = HttpUtility.ParseQueryString(querystring); //getting the list of querystring in NameValueCollection
if (navValues.Count > 0)
{
string[] strQ = navValues.AllKeys;
if(strQ.Length>0)
{
}
}
}
querystring= ?+faqid=12123&h=man //here I want updated querystring which does not have any querystring which is there in my excludeQuerystring
I am confused how to get this, actually I want to make a function which will do this all.
Please suggest!!
EDIT:
I applied new code to resolve above problem, however got little stuck while converting NameValueCollection to querystring again.
protected void Page_Load(object sender, EventArgs e)
{
string querystring = string.Empty;
string excludeList = "cid,intcid,del";
if (!string.IsNullOrEmpty(excludeList))
{
string getFinalString = GetQueryString(excludeList);
getFinalString = "?" + getFinalString;
}
}
public string GetQueryString(string excludeArray)
{
string retQueryString = string.Empty;
if (excludeArray.IndexOf(",") != -1)
{
string[] strArray = excludeArray.Split(",".ToCharArray());
NameValueCollection filtered = new NameValueCollection();
filtered.Add(HttpUtility.ParseQueryString(Request.Url.Query));
if (filtered.HasKeys())
{
foreach (string strMatch in strArray)
{
filtered.Remove(strMatch);
}
retQueryString = filtered.ToString(); //Here I am not able to convert back to querystring, however there are other ways to get it like (http://leekelleher.com/2008/06/06/how-to-convert-namevaluecollection-to-a-query-string/), is there any other way to do that
}
}
return retQueryString;
}
Below is the perfect solution I got it, any comments on this.
string excludeList = "cid,intcid,del";
string getFinalString = Regex.Replace(Regex.Replace(Regex.Replace(Request.Url.Query, #"^\?", "&"), "&(" + excludeList.Replace(",", "|") + ")=[^&]*", "", RegexOptions.IgnoreCase), "^&", "?");
We cannot delete a query string directly like below:
Request.QueryString.Remove("foo")
If you do this, you will get an error - collection is read-only. So, we need to write the below code before deleting the query string.
In C#:
PropertyInfo isreadonly =
typeof(System.Collections.Specialized.NameValueCollection).GetProperty(
"IsReadOnly", BindingFlags.Instance | BindingFlags.NonPublic);
// make collection editable
isreadonly.SetValue(this.Request.QueryString, false, null);
// remove
this.Request.QueryString.Remove("foo");
Hope this will help you !!
yes there is a way to compare two arrays
var array1 = new byte[] { 1, 2, 5, 4 };
var array2 = new byte[] { 1, 2, 3, 4 };
var areEqual = array1.SequenceEqual(array2); //return boolean value True or False

Dynamic Controls not Displaying

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.

Using streamreader to read line containing this "//"?

Read a Text file having any line starts from "//" omit this line and moved to next line.
The Input text file having some seprate partitions. Find line by line process and this mark.
If you are using .Net 3.5 you can use LINQ with a IEnumerable wrapped around a Stream Reader. This cool part if then you can just use a where statement to file statmens or better yet use a select with a regular expression to just trim the comment and leave data on the same line.
//.Net 3.5
static class Program
{
static void Main(string[] args)
{
var clean = from line in args[0].ReadAsLines()
let trimmed = line.Trim()
where !trimmed.StartsWith("//")
select line;
}
static IEnumerable<string> ReadAsLines(this string filename)
{
using (var reader = new StreamReader(filename))
while (!reader.EndOfStream)
yield return reader.ReadLine();
}
}
...
//.Net 2.0
static class Program
{
static void Main(string[] args)
{
var clean = FilteredLines(args[0]);
}
static IEnumerable<string> FilteredLines(string filename)
{
foreach (var line in ReadAsLines(filename))
if (line.TrimStart().StartsWith("//"))
yield return line;
}
static IEnumerable<string> ReadAsLines(string filename)
{
using (var reader = new StreamReader(filename))
while (!reader.EndOfStream)
yield return reader.ReadLine();
}
}
I'm not sure what you exactly need but, if you just want to filter out // lines from some text in a stream... just remember to close the stream after using it.
public string FilterComments(System.IO.Stream stream)
{
var data = new System.Text.StringBuilder();
using (var reader = new System.IO.StreamReader(stream))
{
var line = string.Empty;
while (!reader.EndOfStream)
{
line = reader.ReadLine();
if (!line.TrimStart(' ').StartsWith("//"))
{
data.Append(line);
}
}
}
return data.ToString();
}
Class SplLineIgnorStrmReader:StreamReader // derived class from StreamReader
SplLineIgnorStrmReader ConverterDefFileReadStream = null;
{
//created the Obj for this Class.
Obj = new SplLineIgnorStrmReader(strFile, Encoding.default);
}
public override string ReadLine()
{
string strLineText = "", strTemp;
while (!EndOfStream)
{
strLineText = base.ReadLine();
strLineText = strLineText.TrimStart(' ');
strLineText = strLineText.TrimEnd(' ');
strTemp = strLineText.Substring(0, 2);
if (strTemp == "//")
continue;
break;
}
return strLineText;
This is if u want to read the Text file and omit any comments from that file(here exclude "//" comment).

Resources