Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get single value of List<object>

Tags:

c#

asp.net

I'm a new to ASPX, hope you dont mind if my problem is so simple with somebody.

I use a List<object> selectedValues;

selectedValues=...list of object(item1, item2,..)

Each object has 3 fields: id, title, and content.

foreach (object[] item in selectedValues)
{
  foreach (object value in item)
  {
    string result += string.Format("{0}    ", value);
    Textbox1.Text= result;--> all field is displayed in one Textbox.
  }
}

My problem is: how can I get the single field, I mean:

foreach (object value in item)
            {
                TextBox1.Text = id...???
                TextBox2.Text= title...???
                TextBox3.Text= content...???
}
like image 647
vyclarks Avatar asked Oct 06 '13 07:10

vyclarks


People also ask

How to get a single value from list in c#?

At which point, you would still need to iterate through the list to display each name or whatever you need. Returns the only element of a sequence, and throws an exception if there is not exactly one element in the sequence. patientcode suggest uniqueness, and then . Single() would be better.

Can you have a list of objects in C#?

List in C# is a collection of strongly typed objects. These objects can be easily accessed using their respective index. Index calling gives the flexibility to sort, search, and modify lists if required.

Can we have list of objects?

It's perfectly valid to have a list of objects within an object. Though adding a string to your List of Phone objects will throw an error.


2 Answers

You can access the fields by indexing the object array:

foreach (object[] item in selectedValues)
{
  idTextBox.Text = item[0];
  titleTextBox.Text = item[1];
  contentTextBox.Text = item[2];
}

That said, you'd be better off storing the fields in a small class of your own if the number of items is not dynamic:

public class MyObject
{
    public int Id { get; set; }
    public string Title { get; set; }
    public string Content { get; set; }
}

Then you can do:

foreach (MyObject item in selectedValues)
{
  idTextBox.Text = item.Id;
  titleTextBox.Text = item.Title;
  contentTextBox.Text = item.Content;
}
like image 92
Alex Avatar answered Sep 28 '22 08:09

Alex


Define a class like this :

public class myclass {
       string id ;
       string title ;
       string content;
 }

 public class program {
        public void Main () {
               List<myclass> objlist = new List<myclass> () ;
               foreach (var value in objlist)  {
                       TextBox1.Text = value.id ;
                       TextBox2.Text= value.title;
                       TextBox3.Text= value.content ;
                }
         }
  }

I tried to draw a sketch and you can improve it in many ways. Instead of defining class "myclass", you can define struct.

like image 25
User1551892 Avatar answered Sep 28 '22 09:09

User1551892