手动将数据绑定到Gridview

我需要将我的SQL字段绑定到Gridview列。 我之前做过这个并且效果很好,但是我忘了怎么做了,所以我让ASP.NET AutoGenerate列和它工作,现在我想控制数据绑定,下面是我的代码和我的Gridview。 ..任何协助将不胜感激。

protected void Page_Load(object sender, EventArgs e) { SqlConnection conn = new SqlConnection(Sitecore.Configuration.Settings.GetConnectionString("feedback")); SqlCommand cmd = new SqlCommand("select * from fb_results", conn); DataSet ds = new DataSet(); SqlDataAdapter da = new SqlDataAdapter(cmd); da.Fill(ds); GridView1.DataSource = ds; GridView1.DataBind(); conn.Close(); } 

网格视图:

  Feedback                

好。 所以,关于评论:

这是我个人的经历。 我有一个返回此的SQL查询:

 |-----------------------------------------------| |Column 1 |Column 2 |Column 3 | |---------------|---------------|---------------| |"c1foor1bar" |"c2foor1bar" |"c3foor1bar" | |"c1foor2bar" |"c2foor2bar" |"c3foor2bar" | |"c1foor3bar" |"c2foor3bar" |"c3foor3bar" | |---------------|---------------|---------------| 

我的aspx页面看起来像这样:

     

我的页面加载看起来像这样:

 protected void Page_Load(object sender, EventArgs e) { SqlConnection conn = new SqlConnection(); SqlCommand cmd = new SqlCommand("SELECT * FROM fb_results", conn); DataTable dt = new DataTable(); SqlDataAdapter da = new SqlDataAdapter(cmd); da.Fill(dt); GridView1.DataSource = dt; GridView1.DataBind(); conn.Close(); } 

有两个问题。 首先,我的专栏没有被称为相同。 我可以很容易地改变它们,但它们确实代表了不同的数据,所以我不想这样做。 其次,我带来了太多的数据。 我的解决方案是重建表格:

 protected void Page_Load(object sender, EventArgs e) { SqlConnection conn = new SqlConnection(); SqlCommand cmd = new SqlCommand("SELECT * FROM fb_results", conn); DataTable dt = new DataTable(); SqlDataAdapter da = new SqlDataAdapter(cmd); da.Fill(dt); DataTable newTable = createDataTableTemplate(); foreach (DataRow dr in dt.Rows) { DataRow newRow = newTable.NewRoW(); newRow["strFirst"] = SomeOperation((String) dr["Column 1"]); newRow["strLast"] = SomeOtherOperation((String) dr["Column 2"]); newTable.Rows.Add (newRow); } GridView1.DataSource = newTable; GridView1.DataBind(); conn.Close(); } private DataTable createDataTableTemplate () { DataTable table = new DataTable("Table Title"); DataColumn col1 = new DataColumn("strFirst"); col1.DataType = System.Type.GetType("System.String"); DataColumn col2 = new DataColumn("strLast"); col2.DataType = System.Type.GetType("System.String"); table.Columns.Add (col1); table.Columns.Add (col2); return table; } 

请注意:不使用DataSet ,并且所有BoundField都有runat="server"