GridView Nesnesine Otomatik Satır Numarası Ekleme
Merhaba arkadaşlar bu makalemizde GridView nesnesine PNo sütunu ekleyerek otomatik satır numarasının yazılmasını sağlayacağız. İlk önce GridView nesnesinin AutoGenerateColumns="False" yapın. <Columns></Columns> içine;
<asp:TemplateField HeaderText="PNo">
<ItemTemplate>
<%# Container.DataItemIndex + 1 %>
</ItemTemplate>
<asp:TemplateField>
ekleyin.
Screenshot
Şekil 1
Default.aspx.cs
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
Bind();
}
}
protected void Bind()
{
SqlConnection baglan = new SqlConnection("Data Source=(LocalDB)\\v11.0;AttachDbFilename=|DataDirectory|\\data.mdf;Integrated Security=True;Connect Timeout=30");
SqlCommand komut = new SqlCommand();
SqlDataAdapter da = new SqlDataAdapter(komut);
DataSet ds = new DataSet();
komut.CommandText = "Select * From [dbo].[Personel]";
komut.Connection = baglan;
baglan.Open();
komut.ExecuteNonQuery();
da.Fill(ds);
baglan.Close();
GridView1.DataSource = ds;
GridView1.DataBind();
}
}
Default.aspx
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:GridView ID="GridView1" AutoGenerateColumns="False" runat="server" BackColor="White" BorderColor="#E7E7FF" BorderStyle="None" BorderWidth="1px" CellPadding="3" GridLines="Horizontal">
<AlternatingRowStyle BackColor="#F7F7F7" />
<Columns>
<asp:TemplateField HeaderText="PNo">
<ItemTemplate>
<%# Container.DataItemIndex + 1 %>
</ItemTemplate>
</asp:TemplateField>
<asp:BoundField DataField="Pid" HeaderText="PId" />
<asp:BoundField DataField="Name" HeaderText="Name" />
<asp:BoundField DataField="Surname" HeaderText="Surname" />
<asp:BoundField DataField="Department" HeaderText="Department" />
<asp:BoundField DataField="Mail" HeaderText="Mail" />
</Columns>
<FooterStyle BackColor="#B5C7DE" ForeColor="#4A3C8C" />
<HeaderStyle BackColor="#4A3C8C" Font-Bold="True" ForeColor="#F7F7F7" />
<PagerStyle BackColor="#E7E7FF" ForeColor="#4A3C8C" HorizontalAlign="Right" />
<RowStyle BackColor="#E7E7FF" ForeColor="#4A3C8C" />
<SelectedRowStyle BackColor="#738A9C" Font-Bold="True" ForeColor="#F7F7F7" />
<SortedAscendingCellStyle BackColor="#F4F4FD" />
<SortedAscendingHeaderStyle BackColor="#5A4C9D" />
<SortedDescendingCellStyle BackColor="#D8D8F0" />
<SortedDescendingHeaderStyle BackColor="#3E3277" />
</asp:GridView>
</div>
</form>
</body>
</html>
Bir makalenin daha sonuna geldik. Bir sonraki makalede görüşmek üzere. Bahadır ŞAHİN