日期:2014-05-17 浏览次数:20461 次
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();
}<