How to bind grid in ASP.NET?
- by Abid Ali
I cant bind my Grid. I dont know what I am doing wrong, the grid appears empty when I run the program.
here is my code ::
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
this.BindGrid(this.GridView1);
}
private void BindGrid(GridView grid)
{
SqlCommand cmd = new SqlCommand("Select * from Person", cn);
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataTable dt = new DataTable();
da.Fill(dt);
grid.DataSource = dt;
grid.DataBind();
}
<body>
<form id="form1" runat="server">
<div style="margin-left: 240px">
<asp:GridView ID="GridView1" runat="server" CellPadding="4" ForeColor="#333333"
GridLines="None" Width="856px" AutoGenerateColumns = "false"
ShowFooter = "true" ShowHeader="true" BorderStyle="Groove" CaptionAlign="Top"
HorizontalAlign="Center" onrowdatabound="GridView1_RowDataBound" >
<RowStyle BackColor="#F7F6F3" ForeColor="#333333" />
<Columns>
<asp:BoundField HeaderText="ID" />
<asp:BoundField HeaderText="First Name" />
<asp:BoundField HeaderText="Last Name" />
<asp:BoundField HeaderText="Home Phone #" />
<asp:BoundField HeaderText="Cell #" />
<asp:BoundField HeaderText="Email Address" />
<asp:BoundField HeaderText="NIC #" />
<asp:TemplateField HeaderText="Action">
<ItemTemplate>
<asp:Button ID="Button1" runat="server" Text="Button" />
<asp:Button ID="Button2" runat="server" Text="Button" />
</ItemTemplate>
</asp:TemplateField>
</Columns>
<FooterStyle BackColor="#5D7B9D" Font-Bold="True" ForeColor="White"
/>
<PagerStyle BackColor="#284775" ForeColor="White" HorizontalAlign="Center" />
<SelectedRowStyle BackColor="#E2DED6" Font-Bold="True" ForeColor="#333333" />
<HeaderStyle BackColor="#5D7B9D" Font-Bold="True" ForeColor="White" />
<EditRowStyle BackColor="#999999" />
<AlternatingRowStyle BackColor="White" ForeColor="#284775" />
</asp:GridView>
</div>
</form>
</body>