简体   繁体   中英

Populate Datagridview from different tables c#

I am try to populate a datagridview from 2 different tables which is nonMember and customer with this codes below... but the datagridview doesn't display anything except for a gray background.

using (SqlConnection connection = new SqlConnection(ConnectionString))
        using (SqlCommand cmd = connection.CreateCommand())
        {
            connection.Open();
            cmd.CommandText = "@SELECT tbl_nonMember.*, tbl_customer.customerID AS Expr1, tbl_customer.lname, tbl_customer.fname, tbl_customer.mname, tbl_customer.gender, tbl_customer.age, tbl_customer.membership_type FROM tbl_customer INNER JOIN tbl_nonMember ON tbl_customer.customerID = tbl_nonMember.customerID";
            SqlDataAdapter adap = new SqlDataAdapter(cmd);
            DataSet ds = new DataSet();
            adap.Fill(ds);
            dataGridView2.DataSource = ds.Tables[0].DefaultView;
        }

Try adding this to your method before you set the datasource of dataGridView2.

dataGridView2.AutoGenerateColumns = true;

And your select query should not have @ in the front of the keyword SELECT. It should be:

cmd.CommandText = "SELECT tbl_nonMember.*, tbl_customer.customerID AS Expr1, tbl_customer.lname, tbl_customer.fname, tbl_customer.mname, tbl_customer.gender, tbl_customer.age, tbl_customer.membership_type FROM tbl_customer INNER JOIN tbl_nonMember ON tbl_customer.customerID = tbl_nonMember.customerID";

So I would venture to guess that after auto generating your columns, your Tables[0] did not return any rows because of the invalid select clause.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM