.NET Framework提供DataGrid控件来在网页上显示数据。它是在.NET1.0中引入的,现在已被弃用。DataGrid用于在可滚动的网格中显示数据。它需要数据源来填充网格中的数据。
它是一个服务器端控件,可以从工具箱拖到Web窗体。DataGrid的数据源可以是DataTable或数据库。让无涯教程看一个示例,如何在应用程序中创建一个DataGrid。
本教程包含两个示例。一个是使用DataTable,第二个是使用数据库将数据显示到DataGrid中。
此示例使用DataTable将数据绑定到DataGrid控件。
//DataGridExample2.aspx
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="DataGridExample2.aspx.cs" Inherits="DataGridExample.DataGridExample2" %> <!DOCTYPE html> <html xmlns="http://www.w3.org/1999/xhtml"> <head runat="server"> <title></title> </head> <body> <form id="form1" runat="server"> <div> <p>This DataGrid contains DataTable records </p> <asp:DataGrid ID="DataGrid1" runat="server"> </asp:DataGrid> </div> </form> </body> </html>
//DataGridExample2.aspx.cs
using System; using System.Data; namespace DataGridExample { public partial class DataGridExample2 : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { DataTable table = new DataTable(); table.Columns.Add("ID"); table.Columns.Add("Name"); table.Columns.Add("Email"); table.Rows.Add("101", "Deepak Kumar", "deepak@example.com"); table.Rows.Add("102", "John", "john@example.com"); table.Rows.Add("103", "Subramanium Swami", "subramanium@example.com"); table.Rows.Add("104", "Abdul Khan", "abdul@example.com"); DataGrid1.DataSource = table; DataGrid1.DataBind(); } } }
输出:
它会向浏览器生成以下输出。
此示例使用数据库作为数据源,将数据显示到DataGrid。此示例包括以下步骤。
创建一个新窗体以在其上拖动数据网格。请看,就像无涯教程在下面的屏幕截图中所做的那样。
添加之后,现在打开工具箱并将DataGrid控件拖到窗体上。
拖动之后,它最初看起来如下所示。
链接:https://www.learnfk.comhttps://www.learnfk.com/asp.net_mvc/asp-net-datagrid.html
来源:LearnFk无涯教程网
此表单在后台包含以下源代码。
//DataGridExample.aspx
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="DataGridExample.aspx.cs" Inherits="AdoNetExample.DataGridExample" %> <!DOCTYPE html> <html xmlns="http://www.w3.org/1999/xhtml"> <head runat="server"> <title></title> </head> <body> <form id="form1" runat="server"> <div> </div> <asp:DataGrid ID="DataGrid1" runat="server"> </asp:DataGrid> </form> </body> </html>
在代码后面文件中,无涯教程有数据库连接代码,并将获取记录绑定到DataGrid。
//DataGridExample.aspx.cs
using System; using System.Data; using System.Data.SqlClient; namespace AdoNetExample { public partial class DataGridExample : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { using (SqlConnection con = new SqlConnection("data source=.; database=student; integrated security=SSPI")) { SqlDataAdapter sde = new SqlDataAdapter("Select * from student", con); DataSet ds = new DataSet(); sde.Fill(ds); DataGrid1.DataSource = ds; DataGrid1.DataBind(); } } } }
Student表包含要使用数据网格显示的记录。此表包含以下记录。
输出:
执行此应用程序后,它将从SQL服务器获取记录并显示到Web浏览器。
祝学习愉快!(内容编辑有误?请选中要编辑内容 -> 右键 -> 修改 -> 提交!)