I would like to show content of a table in SQL database to a gridview in C# project, but there is a trouble, the gridview shows nothing.
could you please help me to fix it!
Thanks.
Here is my code:

protected void Page_Load(object sender, EventArgs e)
        {
            if (!this.IsPostBack)
            {

                string cs = ConfigurationManager.ConnectionStrings["SampleDBCS"].ConnectionString;
                SqlConnection con = new SqlConnection(cs);
                SqlCommand cmd = new SqlCommand("select * from newexample", con);

                DataTable dt = new DataTable();
                dt.Columns.Add("col0");
                dt.Columns.Add("col1");
                dt.Columns.Add("col2");

                con.Open();
                SqlDataReader rdr = cmd.ExecuteReader();
                while (rdr.Read())
                {
                    DataRow dr = dt.NewRow();
                    dr["col0"] = rdr["col0"];
                    dr["col1"] = rdr["col1"];
                    dr["col2"] = rdr["col2"];

                    dt.Rows.Add(dr);

                }
                con.Close();

                GridView1.DataSource = dt;
                GridView1.DataBind();
            }

        }

    }
}

Step 1 of troubleshooting is narrowing down the places you need to look. With that in mind, my first question would be whether dt actually contains data or not when you look at it in a debug trace.

If it does, then binding or refreshing the grid would be my next point of tracing. If it doesn't, that's your problem. ;)

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.