c# - 如何将数据添加到我的代码隐藏表中并以 html 形式显示?

标签 c# .net asp.net html

我想从我的服务器提取数据并添加到表对象中。循环遍历数据,然后我想在 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/

相关文章:

c# - 如何区分真实的 http 上下文或请求与假的?

c# - 在 MVC 中使用 Web API DelegatingHandler

asp.net - 如何查找是否从同一台计算机访问两个不同的帐户但使用不同的浏览器?

c# - 创建缩略图会产生质量很差的图像

.net - 使用 dnx 和 Global.json 一次运行所有测试项目

c# - WPF多级绑定(bind)线程问题

c# - HttpWebResponse 的编码问题

c# - 在 WPF 文本框中显示 "current working directory"

c# - 将 onmouseover 事件分配给我的 htmldocument 不起作用

C#发送POST请求并接收303状态码