Search code examples
c#data-binding

How to take the results from an object/model and assign that value to a text-box or another variable. similar to assigning the results to a list-box


I am able to retrieve data from my database via stored procedure and then get that data to display in a list box easy. NOTE i am also using dapper.

Now i want to bind that data in a text-box or a string variable, as the data doesn't need a list box its only one single string.

        //my class is located in a class library



        public string LocationName { get; set; } 

        public string Image_Path { get; set; } 

        public string FullImagepath { get { return Image_Path; } 

        }

I want to display the actual string value in the text-box not the generic list path.

This is the result that i get in the text-box i have replaced my actual project name however.

     System.Collections.Generic.List`1[MY PROJECT NAME.Library.Internal.DataAccess.]

Solution

  • You can't simply print off a list of classes, since C# won't know how to stringify the individual classes.

    Instead, you can select parts of the class to print, using System.Linq, by selecting a string from each class, and then joining them together, like so:

    textBox1.Text = string.Join(loadedLocations.Select(x => x.LocationName), ", ");
    

    Or, if you want to list all properties, you could just use a loop to string build:

    string final = "";
    foreach (var location in loadedLocations)
    {
        final += location.LocationName + " - Image at " + location.Image_Path + "\n";
    }
    textBox1.Text = final;