Auto generate gridview row in asp.net

Description:-

In this article we will see about Auto GenerateGridview Row in Dot net. Here I have created sample demo example to understand easily in dot net. Here I have bind Gridview data from database and display in webpage. For example I have used country table to get data from that table and display on webpage.

I have used Container to get Gridview row Index and add dynamically in Gridview to Increment based on Item Index. To use we have to add it on Itemtemplate in Gridview.

<%# Container.DataItemIndex + 1 %>

Now Bind Gridview data from Database and Display it on Webpage.

Create Table:-
Create Table and Name it "Country".

CREATE TABLE [dbo].[Country](
 [CountryID] [bigint] IDENTITY(1,1) NOT NULL,
 [CountryName] [varchar](50) NULL,
 CONSTRAINT [PK_Country] PRIMARY KEY CLUSTERED 
(
 [CountryID] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
) ON [PRIMARY]

GO

Default.aspx:-

<div>
  <asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="false">
    <HeaderStyle BackColor="#507CD1" Font-Bold="True" ForeColor="White" />
    <AlternatingRowStyle BackColor="#BFE4FF" />
      <Columns>
        <asp:TemplateField HeaderText="Sr.No.">
          <ItemTemplate>
            <%# Container.DataItemIndex + 1 %>
          </ItemTemplate>
        </asp:TemplateField>
        <asp:BoundField DataField="CountryName" HeaderText="CountryName" />
      </Columns>
  </asp:GridView>
</div>

Default.aspx.cs:-

protected void Page_Load(object sender, EventArgs e)
{
  SqlDataAdapter adapter = new SqlDataAdapter();
  DataSet ds = new DataSet();
  int i = 0;
  string sql = null;
  string connetionString = "Data Source=ServerName;Initial Catalog=DatabaseName;Integrated Security=True";
  sql = "select * from Country";
  SqlConnection connection = new SqlConnection(connetionString);
  connection.Open();
  SqlCommand command = new SqlCommand(sql, connection);
  adapter.SelectCommand = command;
  adapter.Fill(ds);
  adapter.Dispose();
  command.Dispose();
  connection.Close();
  GridView1.DataSource = ds.Tables[0];
  GridView1.DataBind();
}

Related Posts

Previous
Next Post »

Thanks for comments.....