asp.net gridview fetch data from database

(1 post) (1 voice)


Reply to this Topic Start new Topic

Custom Search

  1. C_K
    C_K
    Distinguished
    Moderator
    Score: 147

    Using ASP.NET is the easiest way to fetch your data from database and show it on client browser.The code may be written as follows:
    Add one GridView from tool box to your design page.
    Add following two namespaces apart from those added by default:
    using System.Data.SqlClient;
    using System.Data;

    SqlConnection con = new SqlConnection("Server=YourServerName;Initial Catalog=DatabaseName;User=userName;password=yourPassword");
    protected void Page_Load(object sender, EventArgs e)
    {
    if (!Page.IsPostBack)
    {
    BindData();
    }
    }
    public void BindData()
    {
    try
    {
    con.Open();

    SqlDataAdapter da = new SqlDataAdapter("select top 10 * from Employee", con);
    DataTable ds = new DataTable();
    da.Fill(ds);
    GridView1.DataSource = ds;
    GridView1.DataBind();
    }
    catch (Exception ex)
    {
    Label1.Text = ex.Message.ToString();
    }
    finally
    {
    con.Close();
    }
    }

    This will fetch top 10 rows from Employee table in GridView.

    Posted 1 year ago #

Post a Comment

You must log in to post.