日期:2014-05-17  浏览次数:20426 次

菜鸟求助:请一个C# asp.net数据绑定的实例。
从数据库读取表mytable所有 记录,显示在页面上。
表的列比如有ID,Name。

请使用Gridview控件。

请给出ASPX的代码及CS的代码,谢谢。

本人不是没有自己去研究,只是实在没能弄明白,已经花了我两天的时间了,实在是笨吧。

谢谢。

------解决方案--------------------
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="WebForm1.aspx.cs" Inherits="MvcApplication1.WebForm1" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False">
<Columns>
<asp:TemplateField HeaderText="用户ID">
<ItemTemplate>
<asp:Label ID="Label1" runat="server" Text='<%# Bind("uid") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="用户名">
<ItemTemplate>
<asp:Label ID="Label1" runat="server" Text='<%# Bind("username") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
</div>
</form>
</body>
</html>


前台
C# code

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Data.SqlClient;
namespace MvcApplication1
{
    public partial class WebForm1 : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            string connstr = "server=.;uid=sa;pwd=sasa;database=discuz";
            SqlConnection conn = new SqlConnection(connstr);
            SqlCommand comm = new SqlCommand("select * from wkj_users",conn);
            SqlDataAdapter ad = new SqlDataAdapter();
            ad.SelectCommand = comm;
            DataTable dt = new DataTable();
            ad.Fill(dt);
            GridView1.DataSource = dt;
            GridView1.DataBind();
        }
    }
}

------解决方案--------------------
ASPX的代码:
<asp:GridView ID="GridView1" runat="server">
<Columns>
<asp:BoundField DataField="ID" HeaderText="ID"/>//HeaderText为gridview中列的标题名
<asp:BoundField DataField="Name" HeaderText="Name"/>
</Columns>
</asp:GridView>
CS代码:
 public partial class WebForm1 : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if(!IsPostBack)
{
Bind();
}
}

public void Bind()
{
string sql = "连接数据库语句";
string select = "sql语句";
SqlConnection conn = new SqlConnection(sql);
SqlCommand cmd = new SqlCommand(select,conn);
SqlDataAdapter sda = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
sda.Fill(ds);
GridView1.DataSource = ds;
GridView1.DataBind();

}<