Can't bind gridview to datatable in C# web form RRS feed

  • Question

  • Hello all. I can't figure out how to bind a gridview to a datatable on a web form in Visual Studio. I am using SQL to grab data from a table and then want that info to show in a gridview, but cannot figure out how to do it. I should be simple but I can't get it. Here is the code i'm trying

    SqlConnection conn = new SqlConnection("Connection String");
    SqlDataAdapter da = null;
    DataSet ds = null;
    DataTable dt = new DataTable();

    string SQL = @"Select* from myTable";

    da = new SqlDataAdapter(SQL, conn);
    ds = new DataSet();
    da.Fill(ds, "tblCopy");
    dt = ds.Tables["tblCopy"];       

    In the the Designer I add the GridView by dragging a GridView onto the web form. Set the ID to GV and keep the DataSourceID property blank.

    Then in code I add...

    GV.DataSource = dt;

    There is info in the table but not in the GridView. 

    I check it using...

    if (dt.Rows.Count > 0)
                    infoLBL.Text = "dt has info.";
                    infoLBL.Text = "Unable to collect database.";

      if (GV.Rows.Count > 0)
                    infoLBL.Text = "GV has info.";
                    infoLBL.Text = "Unable to populate grid.";

    The table will have info  but the datagrid never does.

    Thanks anyone for any help.

    • Moved by CoolDadTx Thursday, January 24, 2019 3:02 PM ASP.NET related
    Thursday, January 24, 2019 4:49 AM

All replies

  • Did you call DataBind() method after setting DataSource on GridView like below

    GV.DataSource = dt;


    Siva Sankar

    Thursday, January 24, 2019 6:17 AM
  • Yes, I have tried the above code with GV.DataBind() but still get no result.

    GV.DataSource = dt;


    And, when I use "GV.Rows.Count.ToString();" the results a zero.

    Thursday, January 24, 2019 11:32 AM
  • This forum is for questions specifically related to C#. Please post questions related to ASP.NET in the ASP.NET forums.

    Michael Taylor http://www.michaeltaylorp3.net

    Thursday, January 24, 2019 3:01 PM