GridView没有从DataBinding mysql表填充

时间:2012-11-09 04:55:36

标签: c# mysql gridview

您好我正在尝试从MySQL数据库加载表并在asp:GridView组件中显示表的内容。

在.aspx文件中是我的GridView组件。

<asp:GridView ID="ViewUsers" runat="server" 
onselectedindexchanged="ViewUsers_SelectedIndexChanged"  > 
</asp:GridView>

在.aspx.cs文件中我有我的C#代码将数据从MySQL表绑定到GridView。但出于某种原因,它没有这样做。

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using MySql.Data.Common;
using MySql.Data.MySqlClient;
using System.Data.SqlClient;
using System.Windows.Forms;
using System.Data;

public partial class viewAdmin : System.Web.UI.Page
{
    String MyConString = "SERVER=localhost;" +
                "DATABASE=logintable;" +
                "UID=root;" +
                "PASSWORD=;";
protected void Page_Load(object sender, EventArgs e)
{
        if ((String)Session["authorize"] != "1")
        {
            Response.Redirect("Default.aspx");
        }
        MySqlConnection conn = new MySqlConnection(MyConString);
        MySqlCommand cmd = new MySqlCommand("SELECT * FROM logindata;", conn);
        conn.Open();
        DataTable dataTable = new DataTable();
        MySqlDataAdapter da = new MySqlDataAdapter(cmd);

        da.Fill(dataTable);


        ViewUsers.DataSource = dataTable;
        ViewUsers.DataMember = dataTable.TableName;
}

}

GridView假设在我的页面加载时填充。任何帮助是极大的赞赏。哦,我也是ASP.NET的初学者。

1 个答案:

答案 0 :(得分:0)

您需要在GridView上调用DataBind()

ViewUsers.DataSource = dataTable;
ViewUsers.DataBind();

另外,请确保关闭该数据库连接!