How to fill data in gridview in asp net

  • by

In your project make a new .aspx page and edit its as following :

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "">
<html xmlns="">
<head runat="server">
<title>Untitled Page</title>
<form id="form1" runat="server">
<asp:GridView runat="server" ID="datagrid" BackColor="White"
BorderColor="#CCCCCC" BorderStyle="None" BorderWidth="1px" CellPadding="3">
<RowStyle ForeColor="#000066" />
<FooterStyle BackColor="White" ForeColor="#000066" />
<PagerStyle BackColor="White" ForeColor="#000066" HorizontalAlign="Left" />
<SelectedRowStyle BackColor="#669999" Font-Bold="True" ForeColor="White" />
<HeaderStyle BackColor="#006699" Font-Bold="True" ForeColor="White" />

Open your web.config file and add a ConnectionString for making connection to SQL database.

<add name="myconnectionString" connectionString="Data Source=h-pc;Initial Catalog=mydatabase;Persist Security Info=True;User ID=sa;Password=123" />


Open the .cs page (code file) and edit it as following :

using System;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using System.Data.SqlClient;
using System.Data.Sql;

public partial class _Default : System.Web.UI.Page
String myconnectionString = ConfigurationManager.ConnectionStrings["myconnectionstring"].ConnectionString;
SqlConnection con;
SqlDataAdapter adapter;
DataSet ds;
SqlCommand cmd;
protected void Page_Load(object sender, EventArgs e)
con = new SqlConnection(myconnectionString);
cmd = new SqlCommand("select * from mytable", con);
adapter = new SqlDataAdapter(cmd);
ds = new DataSet();
adapter.Fill(ds, "mytable");
datagrid.DataSource = ds.Tables[0];


Furthermore if your are interested in more gridview topics like adding buttons in it,gridview with updatepanel, you can refer these posts :
GridView with update panel in ASP.NET
GridView with Buttons ASP.NET C#
Import csv file to ms sql server using ASP.NET C#

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.