2016-07-22 40 views
-1

所以我不知道我會如何做到這一點,我已經搞了幾個小時無濟於事。如何檢索數據庫中的所有行並存儲在gridview中?

我想從數據庫中獲取所有數據並將其顯示在網格視圖中。

到目前爲止,我已經得到了HTML側

<%@ Page Title="Add a pet type" Language="C#" MasterPageFile="~/Site.Master" AutoEventWireup="true" CodeBehind="PetView.aspx.cs" Inherits="Pets_In_Need.PetView" %> 

<asp:Content ID="BodyContent" ContentPlaceHolderID="MainContent" runat="server"> 
    <div class="starter-template"> 
     <h1>View Pets</h1> 
     <asp:GridView ID="grdViewPets" runat="server" AllowSorting="True" AutoGenerateColumns="False" DataKeyNames="ProductID" EnableViewState="False"> 
      <Columns> 
      <asp:BoundField DataField="name" HeaderText="Name" SortExpression="Pet Name" /> 
      <asp:BoundField DataField="age" HeaderText="Date of Birth" ReadOnly="True" SortExpression="Pet Date of Birth" /> 
      <asp:BoundField DataField="gender" HeaderText="Gender" ReadOnly="True" SortExpression="Pet Gender" /> 
      <asp:BoundField DataField="breed" HeaderText="Breed" ReadOnly="True" SortExpression="Pet Breed" /> 
      <asp:BoundField DataField="weight" HeaderText="Weight(lbs)" ReadOnly="True" SortExpression="Pet Weight" /> 
      <asp:BoundField DataField="friendliness" HeaderText="Friendliness(1-10)" ReadOnly="True" SortExpression="Pet Friendliness" /> 
      </Columns> 
     </asp:GridView> 
    </div> 
</asp:Content> 

這。

using System.Web; 
using System.Web.UI; 
using System.Web.UI.WebControls; 
using System.Data.SqlClient; 
using System.Data; 

namespace Pets_In_Need 
{ 
    public partial class PetView : System.Web.UI.Page 
    { 
     protected void Page_Load(object sender, EventArgs e) 
     { 
      //Create new DB connection 
      DB pinDB = new DB(); 
      //Open DB connection 
      pinDB.Open(); 


     } 
    } 
} 

我該從哪裏出發我已經閱讀了很多其他的文章和教程,但是我似乎無法將它放到我自己的工作中。

任何幫助表示讚賞,謝謝!

回答

3

首先,你需要從數據庫中獲取數據:

 string SelectQuery = "SELECT * FROM [tableName]"; 
     DataTable table = new DataTable(); 
     using (var con = new SqlConnection(ConnectionString)) 
     { 
      using (var da = new SqlDataAdapter(SelectQuery, con)) 
      { 
       //Populate the datatable with the results 
       da.Fill(table); 
      } 
     } 

一旦你有一個DataTable將其綁定到GridView:

 grdViewPets.DataSource = table; 
     grdViewPets.DataBind(); 

你會想,以確保在列DataTable與GridView中的列匹配。

+0

使用(var con = new SqlConnection(ConnectionString)) 感謝這有助於很多,你可以簡單地向我解釋連接字符串部分? – BakedPanda

+0

ConnectionString是一個字符串,包含連接到數據庫所需的所有信息。獲取連接字符串到數據庫的一種簡單方法是使用Visual Studio打開服務器資源管理器(ctrl-alt-s),右鍵單擊數據連接並添加連接。然後輸入IP或DB文件名,如果是本地的,有效的認證等,並選擇默認數據庫。一旦服務器存在於數據連接下,就可以從屬性複製連接字符串。例如:'Data Source =(localdb)\ v11.0; Initial Catalog = StronglyTypedContext-20150714230644; Integrated Security = True' – RIanGillis

相關問題