bind datatable to gridview c# asp.net

C#和ASP.NET中将DataTable绑定到GridView的方法如下:

  • 在ASPX页面中添加GridView控件:
  • <asp:GridView ID="GridView1" runat="server"></asp:GridView>
    
  • 在代码中创建一个DataTable对象并设置其列名和行数据:
  • // Create a new DataTable.
    DataTable table = new DataTable();
    // Add columns to the DataTable.
    table.Columns.Add("ID", typeof(int));
    table.Columns.Add("Name", typeof(string));
    table.Columns.Add("Birthdate", typeof(DateTime));
    // Add rows to the DataTable.
    table.Rows.Add(1, "John Doe", new DateTime(1990, 1, 1));
    table.Rows.Add(2, "Jane Doe", new DateTime(1992, 2, 2));
    table.Rows.Add(3, "Bob Smith", new DateTime(1994, 3, 3));
    
  • 将DataTable绑定到GridView控件:
  • // Bind the DataTable to the GridView.
    GridView1.DataSource = table;
    GridView1.DataBind();
    

    以上代码将绑定DataTable到GridView,其中DataBind()方法是必须的。这将显示一个显示DataTable中数据的GridView控件。如果需要对GridView进行分页或排序,也可以设置其相关属性和事件。

  • 5年前
  •