Gridview没有绑定并显示数据库中的数据

时间:2016-05-21 16:01:44

标签: c# asp.net

好吧,我代表我做了一切,只是为了解决这个问题。我正在尝试使用c#代码在asp.net中使用网格视图从我的数据库打印数据。任何人都可以告诉我什么是错的,以及如何改进我的代码。谢谢。

   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;

            }

2 个答案:

答案 0 :(得分:1)

您必须使用以下数据填充DataSet:

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

答案 1 :(得分:0)

您正在为DataSet分配一个空的DataSource,而不会将DataReader的结果填入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;

    }
}