Svetoslav Panteleev
Svetoslav Panteleev

Reputation: 119

How to show data in DataGridView in C#

I have this class. I want to take data from database (it is working). Make a variable p from class person with data from database and show it in a dataGridView (this isn't working).

public class person {
    public int id { get; set; }
    public string fname { get; set; }
    public string sname { get; set; }
    public string lname { get; set; }
    public string address { get; set; }
    public string username { get; set; }
    public string pass1 { get; set; }
    public string pass2 { get; set; }
    public string email { get; set; }

    public person(int id, string fname, string sname, string lname, string address, string username, string pass1, string pass2, string email)
    {
        this.id = id;
        this.fname = fname;
        this.sname = sname;
        this.lname = lname;
        this.address = address;
        this.username = username;
        this.pass1 = pass1;
        this.pass2 = pass2;
        this.email = email;
    }
}

I read data from database and set it in variable p;

if (reader.HasRows)
{
    reader.Read();
    id = reader.GetInt32(0);
    fname = reader.GetString(1);
    sname = reader.GetString(2);
    lname = reader.GetString(3);
    address = reader.GetString(4);
    username = reader.GetString(5);
    pass1 = reader.GetString(6);
    pass2 = reader.GetString(7);
    email = reader.GetString(8);
    MessageBox.Show("Username found!");
    // Call Close when done reading.
    reader.Close();
    person p = new person(id, fname, sname, lname, address, username, pass1, pass2, email);
    dataGridView1.DataSource = p;
}

but the data doesn't show in dataGridView.

Upvotes: 1

Views: 172

Answers (1)

claudiom248
claudiom248

Reputation: 346

From Microsoft Docs:

The DataGridView class supports the standard Windows Forms data-binding model. This means the data source can be of any type that implements one of the following interfaces:

The IList interface, including one-dimensional arrays.

The IListSource interface, such as the DataTable and DataSet classes.

The IBindingList interface, such as the BindingList class.

The IBindingListView interface, such as the BindingSource class.

You could try passing a list of people instead of a single person to the DataGridView:

var persons = new List<person>() {
    new person(id, fname, sname, lname, address, username, pass1, pass2, email)
};
var bindingList = new BindingList<Person>(list);
var source = new BindingSource(bindingList, null);
dataGridView1.DataSource = source;

Upvotes: 2

Related Questions