I have made a collection to store objects of class sendviaemail
public List<SendViaEmail> email = new List<SendViaEmail>();
The class has a string variable to store emailid. I am adding one object to the list email.
email.Add(s);
Now the s object is of class type email and it contains an emailed(For eg sad#gmail.com)
When I use foreach loop to iterate through all the values in object and add all the emailids in listbox but no data is displayed in listbox
SendViaEmail s = new SendViaEmail();
for (int i = 0; i < s.email.Count(); i++)
{
listBox1.Items.Add(s.email);
}
I tried debugging and in the s object the email = null .
I don't think the code to store email address in the collection works because I m getting null value when I retrieve data.
I m having the email address in string.
How to store string in collection which can hold only objects of class
Firstly, you should be using a Typed List.
That means the List can only contain elements of the SendViaEmail object.
public List<SendViaEmail> email = new List<SendViaEmail>();
You can then add SendViaEmail objects to it.
SendViaEmail s = new SendViaEmail();
email.add(s);
Your loop structure can now take advantage of foreach:
foreach(SendViaEmail s in email){
listBox1.Items.Add(s.email);
}
Try setting the DisplayMember property of listBox1 to "" and then "email".
listBox1.DisplayMember = "";
listBox1.DisplayMember = "email";
This should refresh the view.
Use a foreach loop rather than a for.
foreach (string email in s.email)
{
listBox1.Items.Add(email);
}
If you want to use a for loop, you need to use the index to get the current item.
for (int i = 0; i < s.email.Count(); i++)
{
listBox1.Items.Add(s.email[i]);
}
You are adding the list multiple times, instead of adding each of its element.
This is what you are supposed to do :
SendViaEmail s = new SendViaEmail();
for (int i = 0; i < s.email.Count(); i++)
{
listBox1.Items.Add(s.email[i]);
}
Alternatively, you could use foreach as well :
SendViaEmail s = new SendViaEmail();
foreach (var item in s.email)
{
listBox1.Items.Add(item);
}
Related
I have the following problem. I have a list of strings and want to split these. After that, I want to give each Object Element a reference to an item of the List.
Example:
List<string> valueList = attr.Split(' ').ToList<string>();
This List has items like that:
name,string,age,int
For this example every Object needs to get 2 pieces of information, first the name (out of example: "name" or "age") and second the type (out of example: "string", "int").
Now I want to get an Object with this informations. So I created Objects and put these Objects into a List.
Example:
List<MyObject> listObjects = new List<MyObject>();
for (int i = 0; i < ValueList.Count; i++)
{
MyObject object = new MyObject();
if (ValueList.Any(s => s.StartsWith(modifier)) == true)
{
object.name = ValueList[i];
object.type = ValueList[i + 1];
}
listObjects.Add(object);
}
But with my solution, I'm getting a System.ArgumentOutOfRangeException. My explanation for this would be the foreach but I don't know a technique on how to get every item of the List of strings and add these to objects. Also what a problem is that 1 item of the List should have 2 elements (name, type) but with my method, I'm going through the foreach for every element. Is there any better way to do it in C# .Net Framework?
I suppose that you want something like this.
// Store your relevant keywords in a list of strings
List<string> datatypes = new List<string>{"string", "int"};
// Now loop over the ValueList using a normal for loop
// starting from the second elemend and skipping the next
for(int x = 1; x < ValueList.Count; x+=2)
{
// Get the current element in the ValueList
string current = ValueList[x];
// Verify if it is present in the identifiers list
if (datatypes.Contains(current)))
{
// Yes, then add the element before the current and the current to the MyObject list
MyObject obj = new MyObject;
obj.name = ValueList[x - 1];
obj.type = current;
listObjects.Add(obj);
}
}
I'm using foreach to transfer data from list to another but when adding value updated automatically to last value added. For example:
list1 = [1,2,3]
list2 = new List<Model>()
foreach(var item in list1) {
list2.Add(item)
}
the result in list2 is [ 3, 3, 3]
Actually example is below :
var _sizes = new List<ProductsSize>();
var _size = new ProductsSize();
if (model.Dynamic_ProductsSize.Count > 0)
{
foreach (var item in model.Dynamic_ProductsSize)
{
_size.SizeId = item;
_sizes.Add(_size);
}
}
model.ProductsSize = _sizes.ToList();
I need to know why it only takes the last item and what is the solution for this case
You only have one ProductsSize object:
var _size = new ProductsSize();
And you keep modifying that same object. All references to that object, including any list elements it's been added to, get updated when you modify that one object.
Instead, create your new object in the loop:
foreach (var item in model.Dynamic_ProductsSize)
{
var _size = new ProductsSize();
_size.SizeId = item;
_sizes.Add(_size);
}
That way each element in the list is a new object instead of the same object added multiple times.
Side note, you have a few things in the code which aren't necessary. Checking the length before the loop, for example, as well as converting a list to a list at the end.
In fact, I imagine all of the code shown can be shortened to simply this:
model.ProductsSize = model.Dynamic_ProductsSize.Select(p => new ProductsSize { SizeId = p }).ToList();
In which case you're also just converting one model property to another model property. Why not put this logic in the model itself and skip the whole thing?
public IEnumerable<ProductsSize> ProductsSize
{
get { return this.Dynamic_ProductsSize.Select(p => new ProductsSize { SizeId = p });
}
Unless there's a particular reason you want the same data twice in two different properties that isn't clear from this code, having one set of data and just different views/calculations/etc. of that data is often preferred.
Create a new object before adding it to the list. You can use the object initializer syntax to keep it concise:
if (model.Dynamic_ProductsSize.Count > 0)
{
foreach (var item in model.Dynamic_ProductsSize)
{
_sizes.Add(new ProductsSize(){SizeId = item});
}
}
This is my property class:
class Actions
{
public string[] Style { get; set; }
}
and this is my main method:
Actions action = new Actions();
List<string> list = new List<string>();
list.Add("one");
list.Add("two");
foreach (var item in list)
{
for (int i = 0; i < action.Style.Length; i++)
{
action.Style[i] = item.ToString();
Console.WriteLine(action.Style[i]);
}
}
How do I fill the property with list items?
This gives me a exception:
"object reference not set to an instance of an object".
There is no need to add your items one by one, you could just use the ToArray() method of your list like so:
List<string> list = new List<string>();
list.Add("one");
list.Add("two");
Actions action = new Actions {
Style = list.ToArray()
};
As has already been pointed out, Style is always null, given the code you have shared. #Eldeniz and #paul have shared different ways to fix that. Obviously, your sample code is just a sample fragment, so here are 2 other options you could consider if the previous two don't work for whatever reason (I'm just free-handing this, please excuse any typos).
1) You can have your Actions class always return a not-null object
class Actions
{
private string[] _style;
public string[] Style
{
get { return _style ?? new string[0]; }
set { _style = value; }
}
}
Note that this will allow you to always see the output of the style property as requested, assuming an empty array and null are, for your purposes, the same thing.
2) You can make your loop tolerant to null values
foreach (var item in list)
{
for (int i = 0; i < action?.Style.Length ?? 0; i++)
{
action.Style[i] = item.ToString();
Console.WriteLine(action.Style[i]);
}
}
Finally, just as a tip, if you have your debugger attached and you are stepping through your code, Visual Studio will help you pinpoint these sorts of errors pretty easily. Take the time to become friends with your debugger. If it gives you an error you don't understand, do a quick web search. Your future self will thank you.
You must create an instance of the Style property
List<string> list = new List<string>();
list.Add("one");
list.Add("two");
Actions action = new Actions();
action.Style=new string[list.Count];
foreach (var item in list)
{
for (int i = 0; i < action.Style.Length; i++)
{
action.Style[i] = item.ToString();
Console.WriteLine(action.Style[i]);
}
}
I have some file paths stored in a List and need to attach them to an email. But how can I access the values (in my case: file paths as string values) of my List Items?
Here is the code:
List<string> filesToSend = new List<string>();
filesToSend = (List<string>)Session["filesListForFilesToSend"];
for (int i = 0; i < filesToSend.Count; i++)
{
//message.Attachments.Add(filesToSend[i].????????????????????);
}
Thanks in advance
filesToSend[i] will return the path string you want
Try This
foreach(string EachString in filesToSend)
{
message.Attachments.Add(EachString)
}
First, you do not need to instance a first list the after read the list in session, just:
List<string> filesToSend = (List<string>)Session["filesListForFilesToSend"];
When you access and List by index you will get the object of generic type. You can do it using a lot of ways, for sample:
using for loop:
for (int i = 0; i < filesToSend.Count; i++)
message.Attachments.Add(filesToSend[i]);
or foreach
foreach(string file in filesToSend)
message.Attachments.Add(file);
or while
int i = filesToSend.Lenght;
while(i--)
message.Attachments.Add(filesToSend[i]);
I would use foreach statement, but while will give you more performance (keep in mind you will loop in the reverse order).
The error was not how I was trying to get the string out of my List. The error was how I was trying to attach it to my message.
for (int i = 0; i < filesToSend.Count; i++)
{
string filePath = filesToSend[i];
Attachment attached = new Attachment(filePath);
attached.Name = filePath;
message.Attachments.Add(attached);
}
Thats the way it works for me. Thank you all
I need to create a view for all the lists. The view has to show the fields that are mandatory (is different in every list).
It all goes wrong when the second list is retrieved. The first for-each gives the following error message:
Collection was modified; enumeration operation may not execute
I really don't know why I get this bug.
public override void FeatureActivated(SPFeatureReceiverProperties properties)
{
SPWeb myWeb = SPContext.Current.Web;
SPListCollection myLists = myWeb.GetListsOfType(SPBaseType.DocumentLibrary);
StringCollection viewFields = new StringCollection();
String viewName = "Mandatory fields view";
String query = "<OrderBy><FieldRef Name='Modified'/></OrderBy><Where><Eq><FieldRef Name='Author'/><Value Type='Integer'><UserID Type='Integer' /></Value></Eq></Where>";
foreach (SPList list in myLists)
{
foreach (SPField field in list.Fields)
{
if (field.Required)
{
viewFields.Add(field.ToString());
}
}
list.Views.Add(viewName, viewFields, query, Int32.MaxValue, true, false);
viewFields.Clear();
}
}
Or you could just use a for loop instead of a foreach:
for(int i = 0; i< myLists.Count; i++){
SPList list = myLists[i];
//etc..
}
Try changing foreach (SPList list in myLists) to foreach (SPList list in myLists.ToList()). This will copy the values of myLists to a separate list that can not be modified during each foreach loop.