Alphi
Alphi

Reputation: 55

Gridview not binding and showing datas from my database

well, I've done everything on my behalf just to solve this problem. i'm trying to print the data from my database using grid view in asp.net using c# codes. can anyone tell me whats wrong and how to improve my codes. thank you.

   using (MySqlConnection con = new MySqlConnection(ConfigurationManager.ConnectionStrings["DBCon"].ConnectionString))
        {
            constructor var = new constructor();
            con.Open();
            string sql = "SELECT first_name,last_name,username,contact_number,address,email FROM user_tbl WHERE user_type='2'";
            MySqlCommand cmd = new MySqlCommand(sql, con);
            MySqlDataReader reader1 = cmd.ExecuteReader();
            reader1.Close();

            try
            {                   
                    MySqlDataAdapter da = new MySqlDataAdapter(cmd);
                    DataSet ds = new DataSet();
                    GridView1.DataSource = ds;
                    GridView1.DataBind();
            }

            catch (Exception ex)
            {
                lblresult.Text = "ERROR>>" + ex.Message + "!";
            }

            finally
            {
                con.Close();
                sql = null;

            }

Upvotes: 0

Views: 1434

Answers (2)

Zein Makki
Zein Makki

Reputation: 30022

You're assigning an empty DataSet to your DataSource, without filling the results of your DataReader into the DataSet/DataTable.

using (MySqlConnection con = new MySqlConnection(""))
{
    con.Open();
    string sql = "SELECT first_name,last_name,username,contact_number,address,email FROM user_tbl WHERE user_type='2'";
    MySqlCommand cmd = new MySqlCommand(sql, con);

    try
    {
        DataTable dt = new DataTable();
        using (MySqlDataReader reader1 = cmd.ExecuteReader())
        {
            dt.Load(reader1);
        }

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

    catch (Exception ex)
    {
        lblresult.Text = "ERROR>>" + ex.Message + "!";
    }

    finally
    {
        con.Close();
        sql = null;

    }
}

Upvotes: 0

Abdellah OUMGHAR
Abdellah OUMGHAR

Reputation: 3745

You must fill the DataSet with data like this :

MySqlDataAdapter da = new MySqlDataAdapter(cmd);
DataSet ds = new DataSet();
da.Fill(ds, "TableName");
GridView1.DataSource = ds.Tables["TableName"];
GridView1.DataBind();

Upvotes: 1

Related Questions