Hi I am trying to load table from MySQL database and show contents of table in a asp:GridView component.
In .aspx file is where my GridView Component is.
<asp:GridView ID="ViewUsers" runat="server"
onselectedindexchanged="ViewUsers_SelectedIndexChanged" >
</asp:GridView>
In .aspx.cs file is where I have my C# code to Bind the data from MySQL table to the GridView. But for some reason its not doing it.
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;
}
}
The GridView Is suppose to be populated when my page is loaded. Any help is greatly appreciated. Oh and Im also a beginner in ASP.NET.
You need to call
DataBind()on the GridView.Also, make sure you close that database connection!