且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何使用ASP.NET将mysql数据库中的数据显示到HTML表中

更新时间:2023-10-07 16:22:58

您可以使用转发器来构建几乎任何想要的html,包括表格.绑定的方式会有所不同,但这是针对DataTable的.

You can use a repeater to build pretty much any html you want, including a table. How this works will differ depending on what you''re binding to it, but this is for a DataTable

<asp:Repeater runat="server" ID="MyRepeater">
    <HeaderTemplate>
        <table>
            <tr>
                <th>ID</th>
                <th>Name</th>
            </tr>
    </HeaderTemplate>
    <ItemTemplate>
        <tr>
            <td>
                <%# Eval("ID") %>
            </td>
            <td>
                <%# Eval("Name") %>
            </td>
        </tr>
    </ItemTemplate>
    <FooterTemplate>
        </table>
    </FooterTemplate>
</asp:Repeater>



背后的代码



Code behind

DataTable data = new DataTable();

data.Columns.Add("ID", typeof(int));
data.Columns.Add("Name", typeof(string));

data.Rows.Add(1, "John");
data.Rows.Add(2, "Dave");

MyRepeater.DataSource = data;
MyRepeater.DataBind();


使用GridView并设置DataSource属性.
在此处查看示例:分步进行将MySQL数据绑定到ASP.NET GridView [ HTML页面中的MySQL数据库 [ ^ ]
javascript-如何使用jQuery运行MySQL查询? -堆栈溢出 [ ^ ]
Use a GridView and set the DataSource property.
See example here: Step By Step Bind MySQL Data To ASP.NET GridView[^]
Another way is to use PHP: MySQL database in HTML page[^]
javascript - How can I use jQuery to run MySQL queries? - Stack Overflow[^]


如果只需要基本的HTML输出,则Repeater很好.但是,如果要支持对结果进行分页,对结果进行排序,内联编辑或其他各种高级"功能,则必须跳过几个步骤.

这就是为什么我倾向于使用 ListView控件 [
The Repeater is fine if you just want basic HTML output. But if you want to support paging the results, sorting the results, in-line editing, or various other "advanced" features, you''ll have to jump through a few hoops.

That''s why I tend to prefer the ListView control[^]:
<asp:ListView runat="server" ID="MyListView">
<LayoutTemplate>
    <table class="table table-striped table-bordered">
        <thead>
            <tr>
                <th>ID</th>
                <th>Name</th>
            </tr>
        </thead>
        <tbody>
            <tr id="itemPlaceholder" runat="server" />
        </tbody>
    </table>
</LayoutTemplate>
<ItemTemplate>
    <tr>
        <td>
            <%# Eval("ID") %>
        </td>
        <td>
            <%# Eval("Name") %>
        </td>
    </tr>
</ItemTemplate>
</asp:ListView>