TblStudent表:
动态网页aspx前台:
<body>
<form id="form1" runat="server"><div>
<asp:Table ID="Table1" runat="server">
</asp:Table>
</div>
</form>
</body>
动态网页后台:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data.SqlClient;
namespace demo3
{
public partial class SelectAll : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
string constr = "data source=.;initial catalog=School;User ID=sa;Password=111111";
using (SqlConnection con = new SqlConnection(constr))
{
string sql = "select * from TblStudent";
using (SqlCommand cmd = new SqlCommand(sql, con))
{
con.Open();//
using (SqlDataReader reader = cmd.ExecuteReader())
{
if (reader.HasRows)//HasRows属性,可以判断这次查询有没有结果集返回。有为true,否则为false
{
while (reader.Read())
{
TableRow trRow = new TableRow();
TableCell tcCell;
for (int i = 0; i < 8; i++)
{
tcCell = new TableCell();
tcCell.BorderStyle = BorderStyle.Solid;
tcCell.BorderWidth = 1;
tcCell.Text = reader.GetValue(i).ToString();
trRow.Cells.Add(tcCell);
}
Table1.Rows.Add(trRow);
/*
TableRow trRow = new TableRow();
TableCell tcCell;
for (int i = 0; i < 8; i++)
{
tcCell = new TableCell();
tcCell.BorderStyle = BorderStyle.Solid;
tcCell.BorderWidth = 1;
tcCell.Text = reader.GetValue(i).ToString();
trRow.Cells.Add(tcCell);
}
Table1.Rows.Add(trRow);
TableRow trRow = new TableRow();
//获取第一条记录的第一列中的值。
//reader.GetValue(0).ToString();
TableCell tcCell = new TableCell();
tcCell.BorderStyle = BorderStyle.Solid;
tcCell.BorderWidth = 1;
tcCell.Text = reader.GetValue(0).ToString();
trRow.Cells.Add(tcCell);
//获取第一条记录的第2列中的值。
tcCell = new TableCell();
tcCell.BorderStyle = BorderStyle.Solid;
tcCell.BorderWidth = 1;
tcCell.Text = reader.GetValue(1).ToString();
trRow.Cells.Add(tcCell);
//获取第一条记录的第3列中的值。
tcCell = new TableCell();
tcCell.BorderStyle = BorderStyle.Solid;
tcCell.BorderWidth = 1;
tcCell.Text = reader.GetValue(2).ToString();
trRow.Cells.Add(tcCell);
//获取第一条记录的第4列中的值。
tcCell = new TableCell();
tcCell.BorderStyle = BorderStyle.Solid;
tcCell.BorderWidth = 1;
tcCell.Text = reader.GetValue(3).ToString();
trRow.Cells.Add(tcCell);
//获取第一条记录的第5列中的值。
tcCell = new TableCell();
tcCell.BorderStyle = BorderStyle.Solid;
tcCell.BorderWidth = 1;
tcCell.Text = reader.GetValue(4).ToString();
trRow.Cells.Add(tcCell);
//获取第一条记录的第6列中的值。
tcCell = new TableCell();
tcCell.BorderStyle = BorderStyle.Solid;
tcCell.BorderWidth = 1;
tcCell.Text = reader.GetValue(5).ToString();
trRow.Cells.Add(tcCell);
//获取第一条记录的第7列中的值。
tcCell = new TableCell();
tcCell.BorderStyle = BorderStyle.Solid;
tcCell.BorderWidth = 1;
tcCell.Text = reader.GetValue(6).ToString();
trRow.Cells.Add(tcCell);
//获取第一条记录的第8列中的值。
tcCell = new TableCell();
tcCell.BorderStyle = BorderStyle.Solid;
tcCell.BorderWidth = 1;
tcCell.Text = reader.GetValue(7).ToString();
trRow.Cells.Add(tcCell);
Table1.Rows.Add(trRow);*/
}
}
}
}
}
}
}
}
运行结果: