简体   繁体   中英

How to populate a datagrid view from a SQL Server database in C#

I modified the table so that it has the correct number of records and displays the number of rows on the table but doesn't populate the table at all.

Here is my code:

public TableOutput()
{
    InitializeComponent();
    FillData();
}

void FillData()
{
    string connectionString = @"Data Source = (LocalDB)\MSSQLLocalDB; AttachDbFilename = C:\Users\14142\source\repos\ComputingProject\ComputingProject\computingProject.mdf; Integrated Security = True; Connect Timeout = 30";

    using (SqlConnection c = new SqlConnection(connectionString))
    {
        c.Open();

        using (SqlDataAdapter a = new SqlDataAdapter("SELECT Client, Cost, Description FROM jobs", c))
        {                   
            DataTable t = new DataTable();
            a.Fill(t);

            dataGridView1.DataSource = t;
            dataGridView1.Update();
        }
    }
}

probably you have not declared the columns in the gridview. so try this before setting the datasource:

dataGridView1.AutoGenerateColumns = true; 

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