Site icon ParallelCodes

How to fill data in gridview in asp net

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" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>Untitled Page</title>
</head>
<body>
<form id="form1" runat="server">
<div>
<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" />
</asp:GridView>
</div>
</form>
</body>
</html>

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

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

</connectionStrings>

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);
con.Open();
adapter = new SqlDataAdapter(cmd);
ds = new DataSet();
adapter.Fill(ds, "mytable");
datagrid.DataSource = ds.Tables[0];
datagrid.DataBind();
con.Close();
}
}

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#
STYLING THE GRIDVIEW IN ASP.NET
Enjoy!!!!


Exit mobile version