how to add items from listbox to textbox c# - c#

I was doing an ITP project. I needed to add all the items in the listbox to a textbox. The code that i tried using was:
tbxReceipt.Text = "The items you purchased are:\r\n\r\n" + lbxItemBought.Items.ToString()
+ "\r\n\r\nYour total price was:" + lblLastCheckout.Text;
But when i use the code lbxItemBought.Item.ToString(), it comes up with the error:
System.Windows.Forms.ListBox+ObjectCollection.
I was wondering if there was another way to do it?
thanks

You need to iterate through listbox.
string value = "The items you purchased are:\r\n\r\n";
foreach (var item in lbxItemBought.Items)
{
value += "," + item.ToString();
}
value += "\r\n\r\nYour total price was:" + lblLastCheckout.Text ;
tbxReceipt.Text = value;

Firstly, if you are doing string manipulation with a loop, use a StringBuilder
Now try
StringBuilder a = new StringBuilder();
a.Append("The items you purchased are:\r\n\r\n");
foreach (var item in lbxItemBought.Items)
{
a.Append(item.ToString());
}
a.Append("\r\nYour total price was:");
a.Append(lblLastCheckout.Text);
tbxReceipt.Text = a.ToString();

That message is no error, it is just the string representation of the Items-property of your listbox.
When you want to get a concatenation of the item names (for example), you must iterate over the Items-collection, cast the single elements to the things you put into it and then concatenate a display string. For example, if the type of your items is SomeItem and it has a property like Name, you can use LINQ like this:
var itemNames = string.Join(", ", lbxItemBought.Items
.Cast<SomeItem>()
.Select(item => item.Name));
tbxReceipt.Text = "The items you purchased are:\r\n\r\n" + itemNames + "\r\n\r\nYour total price was:" + lblLastCheckout.Text;

string result = string.Empty;
foreach(var item in lbxItemBought.Items)
result + = item.ToString()+Environment.NewLine;
txtReceipt.Text = result;

Related

C# - Public string only stores last value outside of collection

I am using HtmlAgilityPack to find all items, colours and links to products on a website. I want to be able to find an item on the website by typing in the name and colour inside my application.
So far what I have working is:
The application finds items using only the item name and returns the last thing on the website with that name. There are multiple products with the same name but each have a different colour.
The problem comes in when including colour because it's in a different XPath so it's stored in a different collection.
Here is my code:
HtmlNodeCollection collection = doc.DocumentNode.SelectNodes("//*[contains(#class,'inner-article')]//h1//a");
HtmlNodeCollection collection2 = doc.DocumentNode.SelectNodes("//*[contains(#class,'inner-article')]//p//a");
foreach (var node2 in collection2)
{
string coloursv = node2.InnerHtml.ToString();
strColour = coloursv;
//txtLog.Text += Environment.NewLine + (DateTime.Now.ToString("hh:mm:ss")) + str; - This code returns all colours (If code is ran outside of collection then only last colour in string is returned.
}
foreach (var node in collection)
{
string href = node.Attributes["href"].Value;
var itemname = node.InnerHtml.ToString();
if (itemname.Contains(txtKeyword.Text))
{
txtLog.Text = (DateTime.Now.ToString("hh:mm:ss")) + " - Item Found: " + href + " " + itemname + " " + strColour; //Successfully returns item name, colour and link but always gives last availible on website
}
}
This is because you are continually setting the Text property of a textbox within a loop (so each item will continually overwrite the previous):
foreach (var node in collection)
{
// Omitted for brevity
// This will continually overwrite the contents of your Text property
txtLog.Text = ...;
}
If you want to store multiple items, you'll either need to store the results in some type of a collection object (such as a ListBox, etc.) or by simply concatenating your values into the textbox:
foreach (var node in collection)
{
// Omitted for brevity
var stringToAdd = ...;
txtLog.Text += stringToAdd + Environment.NewLine;
}
You can also accomplish this by using the StringBuilder class to be a bit more efficient:
StringBuilder sb = new StringBuilder();
foreach (var node in collection)
{
// Omitted for brevity
var stringToAdd = ...;
// Append this item to the results
sb.AppendLine(stringToAdd);
}
// Store the results
txtLog.Text = sb.ToString();

Extracting field values from IEnumerable

I have a variable results which holds ResultView as shown below:
In turn StoryQ.Execution.Result IEnumerable will hold values:
I need to extract text representation like " Story is Story". How can I achieve this. Could anyone help me on this. Thanks
Solution is to use select in conjunction with string format.
.Select( c => new {Story_Prefix_Text = string.Format("{0} {1}" ,c.Prefix, c.Text)})
or without lambda
from currentpath in collection
select new { Story_Prefix_Text = currentpath.Prefix + " " + currentpath.Text };
Answering my own question just in case it would help somebody in future.
The problem was solved by converting IEnumerable to List and then iterating through foreach loop. Code snippet is below:
var textFormat = ((IStepContainer)v).SelfAndAncestors().Reverse().ToList();
foreach (var text in textFormat)
{
var StoryInText = text.Step.Prefix + " " + text.Step.Text;
}

List, strings and vs Template

I'm having a list of strings whit some values and I want to make some kind of variable for keeping code that I will be using in template file.
For example lets say I have list with this 3 string values: configService, scaleCoefConfigService, sessionService. Name of the list is chItemName.
And I need to generate this kind of code that I will parse later into template:
[Dependency("configService")]
[Dependency("scaleCoefConfigService")]
[Dependency("sessionService")]
So my question is can make some variable and mechanism for iterating thou list of strings that adds every single item from list to variable?
I've tried this:
foreach (var tp in controllerChecked)
{
var genCode = "[Dependency](" '"' + chItemName + '"'")] \n"
}
controllerChecked is collection of objects and one of the objects value is Name that I'm getting like this:
var chItemName = controllerChecked.Select(c => c.Name).ToList();
This is how the list chItemName is getting those strings.
But of course it is impossible to use + with lists and this kind of stuff will never work. Someone has better idea?
In your example, you are not using the tp variable, which contains will contain each of the values within controllerChecked, one at a time.
You could just iterate through the chItemName list and add the result to a StringBuilder:
StringBuilder codeBuilder = new StringBuilder();
foreach (string tp in chItemName)
{
codeBuilder.AppendLine("[Dependency(\"" + tp + "\")]");
}
string code = codeBuilder.ToString();
If controllerChecked contains more information, you could also directly access it:
StringBuilder codeBuilder = new StringBuilder();
foreach (var item in controllerChecked)
{
string propertyName = item.Name.SubString(1);
codeBuilder.AppendLine("[Dependency(\"" + item.Name + "\")]");
codeBuilder.AppendLine("public " + item.Type + " " + propertyName + " { get; set; }");
codeBuilder.AppendLine();
}
string code = codeBuilder.ToString();
PS. I would definitely change the name of chItemName to chItemNames as it is a list, but that is up to you of course.
This worked perfectly good. I have little bit harder version of this, if you can figure out how to do this:
Lets say that instead of one chItemName list I have 2 more: fName and chItemType, both are string lists.
And I have to generate this kind of code:
[Dependency("alarmsService")]
public IAlarmsService AlarmsService { get; set; }
[Dependency("jsonFactory")]
public IJSONFactoryService JsonFactory { get; set; }
[Dependency("dataBean")]
public IDataBean DataBean { get; set; }
alarmsServise, jsonFactory and dataBean are items of chItemName.
IAlarmsService, IJSONFactoryService and IDataBean are items of chItemType.
AlarmsService, Json Factory and DataBean are items of fName list.
fName is list that I got from chItemType by trimming the first letter from each string in list:
List<string> fName = new List<string>();
foreach(var i in chItemType)
{
var newName = i.Remove(0,1);
fName.Add(newName);
}
So only that list is not a part of controllerChecked list. The othere two are defined like this:
var chItemType = controllerChecked.Select(c => c.Type).ToList();
var chItemName = controllerChecked.Select(c => c.Name).ToList();
Can I edit foreach somehow or maybe I can make parts of code with StringBulider and after that merged them together?

What is the best way to display string items stored in Enumerable<string> object?

This may seem an easy question, but is there a best way in terms of the method or syntax for displaying items stored in an Enumerable object of type string in a TextBox? (and other controls)
I have the following code:
if (CategoryTypes.Count() >= 1)
{
foreach (var category in CategoryTypes)
{
txtCategories.Text += category + ", ";
}
}
Is there a better way of doing this?
txtCategories.Text = string.Join<string>(", ", CategoryTypes);
Assuming that CategoryTypes is a string array. You could do
txtCategories.Text = string.Join(CategoryTypes, ", ");

using LINQ how can i concatenate string properties from itesm in a collection

i have a list of objects in a collection. Each object has a string property called Issue. I want to concatenate the issue from all of the items in the collection and put them into a single string. what is the cleanest way of doing this using LINQ.
here is manual way:
string issueList = "";
foreach (var item in collection)
{
if (!String.IsNullOrEmpty(item.Issue)
{
issueList = issueList + item.Issue + ", ";
}
}
//Remove the last comma
issueList = issueList.Remove(issueList.Length - 2);
return issueList;
You can write
return String.Join(", ", collection.Select(o => o.Issue));
In .Net 3.5, you'll need to add .ToArray().
You could use ToDelimitedString from morelinq.

Categories

Resources