我想从我的服务器提取数据并添加到表对象中。循环遍历数据,然后我想在 aspx 页面上显示结果。
DataTable dTable = new DataTable();
dTable.Columns.Add("idNum", typeof(Int64));
dTable.Columns.Add("Name", typeof(String));
dTable.Columns.Add("Age", typeof(Int64));
//Connection/Command/Statement
DataReader dr = command.ExecuteReader();
while (dr.Read()) { /*Add data to rows*/ }
如何将数据添加到行中?在 aspx 上显示的最佳方式是什么?
最佳答案
试试这个代码,我在本地测试过:
protected void Page_Load(object sender, EventArgs e)
{
if (Page.IsPostBack)
return;
BindDG();
}
private void BindDG()
{
SqlConnection connection = new SqlConnection("Data Source=servername;Initial Catalog=dbname;Integrated Security=True");
using (connection)
{
SqlCommand command = new SqlCommand("select * From staff;",connection);
connection.Open();
SqlDataReader reader = command.ExecuteReader();
if (reader.HasRows)
{
DataTable dt = new DataTable();
dt.Columns.Add("ID", typeof(int));
dt.Columns.Add("Name", typeof(string));
dt.Columns.Add("Age", typeof(int));
while (reader.Read())
{
int id = (int)reader["id"];
string name = reader["name"].ToString();
int age = (int)reader["age"];
dt.Rows.Add(id, name, age);
}
GridView1.DataSource = dt;
GridView1.DataBind();
}
else
{
Reponse.Write("No records found.");
}
reader.Close();
}
}
关于c# - 如何将数据添加到我的代码隐藏表中并以 html 形式显示?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3960838/