bar
bar

Reputation: 25

System.Data.DataRowView c#

Whenever I run this code I get back - System.Data.DataRowView. I don't understand what the problem. I have tried to looking here for solutions but I can't understand (I'm new in programing..).

public void loadLabels()
    {

        using (OleDbConnection connection = new OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + dbString))
        {
            connection.Open();


            String strDa = "SELECT Lessons.number, Lessons.type, Lessons.datel, Lessons.hour , Lessons.money, Lessons.note FROM Lessons";
            using (OleDbDataAdapter da = new OleDbDataAdapter(strDa, connection))
            {
                DataTable t = new DataTable();
                da.Fill(t);

                listBox1.DataSource = t;

            }

        }
    }

Upvotes: 0

Views: 589

Answers (1)

Steve
Steve

Reputation: 216293

The ListBox control takes each element of your DataTable and builds a elements for its Items property. But when it adds an element it doesn't know which one of your database fields should be showed in each of the strings added to the collection. In this case it uses the ToString method of the object used to add the elements. In your case is the ToString method of the DataRowView class. But the DataRowView class doesn't implement any particular ToString() method thus the base implementation (object.ToString()) is called and this returns simply the name of the class.

You could change this behavior using the properties

 listBox1.DataSource = t;
 listBox1.DisplayMember = "datel";
 listBox1.ValueMember = "number";

This will show just one column of your query. If you want to show more than one column you have two options. Ditch the ListBox control and use a DataGridView (there are a lot of examples in this site, use the search function) or create an alias in your query to concatenate together more than one field

String strDa = @"SELECT Lessons.number, Lessons.type, Lessons.datel, 
                Lessons.hour, Lessons.money, Lessons.note,
                Lessons.datel & ' ' & Lessons.hour & ' - ' & Lessons.money as LessonDetails
                FROM Lessons";

....
listBox1.DisplayMember = "LessonDetails";

This is a bit clunky and produces a not very neat display. I recommend to use a DataGridView for this task

Upvotes: 1

Related Questions