如何在ASP.NET中绑定网格?

时间:2011-02-18 05:32:21

标签: c# asp.net

我无法绑定我的网格。我不知道我做错了什么,当我运行程序时,网格显示为空。

这是我的代码::

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>

3 个答案:

答案 0 :(得分:6)

您似乎没有在绑定字段示例中与数据绑定挂钩:

<asp:boundfield datafield="ID" headertext="ID"/>

您可以在msdn上找到如何设置数据绑定字段的完整示例:here

答案 1 :(得分:0)

试试这个:

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();
    }
  }
}

答案 2 :(得分:0)

或者,如果您不想使用绑定字段,请删除以下内容

AutoGenerateColumns =“ false”