2011-12-01 22 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

相关问题