2011-12-01 24 views
1

這裏的情況:如何在asp.net中使用Eval從數據庫中讀取字段?

我有一個webform需要從.aspx頁面中使用eval函數的數據庫讀取特定字段。我知道如何分配.aspx頁面中的值,但是在如何獲取值並將它們綁定到.aspx頁面的代碼背後?我可以只使用數據讀取器嗎?數據集?我究竟是要綁定還是閱讀數據集或讀者?我需要創建一個方法嗎?

我已經創建了存儲過程來從數據庫中提取數據。我打算用存儲過程創建一個方法。我只是不要創建哪種類型的數據集,datareader?我如何在後面的代碼中編碼?

回答

0

聲明公共屬性爲您數據庫字段:

public int MyFieldID = 0; 
public string MyStringFromDB = string.empty; 

// PAGE LOAD GET DB VALUES 
{ 
    MyFieldID = Convert.ToInt32(db["ID"]); 
    MyStringFromDB = Convert.ToString(db["FIELD"]); 
} 

現在,您可以只爲它們分配在aspx頁面像<%= MyFieldID %>或在後面的代碼中使用它們。

+0

好的,太棒了!那麼我應該使用datareader從數據庫中獲取初始數據,然後將值分配給這些字段? – Jeff

+0

是的,您可以使用數據讀取器,數據表或任何其他數據源。我通常將我的數據集作爲數據表返回。但這是你的個人選擇。請記住,DataBinder僅用於將數據綁定到控件(DataGrid,作爲示例)。我是一個經典的ASP開發人員,這很難讓我掌握。 –

+0

工作。謝謝! – Jeff

0

Walkthrough: Displaying Data Using a Stored Procedure in the GridView Web Server Control

您只能在數據綁定控件,如GridView控件,中繼器,數據網格等的上下文中使用的DataBinder.Eval見DataBinder Class

<%@ Page Language="C#" %> 
<%@ Import Namespace="ASPSample" %> 
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> 
<script runat="server"> 
protected void Page_Load(object sender, EventArgs e) 
{ 
     // Create and populate an ArrayList to store the products. 
     ArrayList ProductList = new ArrayList(); 
     ProductList.Add(new Product("Standard", 99.95)); 
     ProductList.Add(new Product("Deluxe", 159.95)); 

     // Bind the array list to Repeater 
     ListRepeater.DataSource = ProductList; 
     ListRepeater.DataBind(); 
} 
</script> 

<html xmlns="http://www.w3.org/1999/xhtml"> 
<head> 
    <title>DataBinder Example</title> 
</head> 
<body> 
<form id="Form2" runat="server"> 
<table> 
<asp:Repeater id="ListRepeater" runat="server"> 
    <HeaderTemplate> 
    <tr> 
     <th style="width:50; text-align:left">Model</th> 
     <th style="width:100; text-align:right">Unit Price</th> 
    </tr> 
    </HeaderTemplate> 
    <ItemTemplate> 
    <tr> 
     <!-- Databind to the Product information using the DataBinder methods. 
      The Container.DataItem refers to the ArrayList object bound to 
      the ASP:Repeater in the Page Load event. --> 
     <td> 
      <%#DataBinder.GetPropertyValue(Container.DataItem, "Model")%> 
     </td> 
     <!-- Format the UnitPrice as currency. ({0:c}) --> 
     <td style="text-align:right"> 
      <%#DataBinder.GetPropertyValue(Container.DataItem, 
         "UnitPrice", "{0:c}")%> 
     </td> 
    </tr> 
    </ItemTemplate> 
</asp:Repeater> 
</table> 
</form> 
</body> 
</html> 
+0

我沒有顯示在gridview中。我在.aspx頁面中使用EVAL函數。 – Jeff

+0

你如何使用Eval? – jrummell

+0

要在.aspx頁面上加載的字段示例: Strength:
<%#DataBinder.Eval(Container.DataItem,「Strength」 )%> Jeff

相關問題