13 March 2014

Gridview with mysql database in asp.net

Asp.net Code

<asp:GridView ID="gv_user" runat="server"></asp:GridView>

C#.net  Code

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Data.Odbc;
using System.Configuration;

namespace Adi.Web
{
    public partial class WebForm1 : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            bind_data();
        }

        public void bind_data()
        {
            try
            {
                using (OdbcConnection connection = new OdbcConnection(ConfigurationManager.ConnectionStrings["MySQLConnStr"].ConnectionString))
                {
                    connection.Open();
                    using (OdbcCommand command = new OdbcCommand("SELECT id, name FROM test_users", connection))
                    using (OdbcDataReader dr = command.ExecuteReader())
                    {
                        gv_user.DataSource = dr;
                        gv_user.DataBind();
                        dr.Close();

                    }
                    connection.Close();
                }
            }
            catch (Exception ex)
            {
                Response.Write("An error occured: " + ex.Message);
            }
        }

    }
}

No comments:

Post a Comment