Reputation: 1747
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>
Upvotes: 0
Views: 12546
Reputation: 1
Or if you do not want to use bound field, then delete the following
AutoGenerateColumns = "false"
Upvotes: 0
Reputation: 1709
It looks like you aren't hooking up to the databinding in your Bound fields example:
<asp:boundfield datafield="ID" headertext="ID"/>
you can find a full example of how to set up a databound field on msdn:here
Upvotes: 6
Reputation: 1813
Try this:
private void BindGrid(GridView grid)
{
using(SqlConnection cn = new SqlConnection("Some Connection string"))
using(SqlCommand cmd = new SqlCommand("Select * from Person", cn))
{
cmd.CommandType = CommandType.Text;
cmd.Connection.Open();
using(SqlDataAdapter da = new SqlDataAdapter(cmd))
{
DataTable dt = new DataTable();
da.Fill(dt);
grid.DataSource = dt;
grid.DataBind();
}
}
}
Upvotes: 0