close

除了DataBinding(幾乎寫在後端程式)之外還有另一種DataBinding Expression,可以撰寫於前端HTML畫面中,配合後端程式碼來顯現資料庫中取出的資料。

 

DataBinding Expression:

分成兩種:

1.單向連結: <%# Eval("欄位名稱") %>

只是用來呈現資料(唯讀不修改)。

2.雙向連結: <%# Bind("欄位名稱") %>

呈現資料外,可以修改或刪除資料。(常用於編輯或更新)。

 

這邊用formview來做,formview特色是畫面都要自己做(所以前端跟資料的DataBinding Expression程式碼也格外重要)。

這邊不搭配SqlDataSource,只單純拉進一個formview。

所以要跟我們自己寫ADO程式去資料庫撈出的資料做DataBinding Expression。

 

前端程式碼:

<asp:FormView ID="FormView1" runat="server">
<ItemTemplate>
id:<asp:Label ID="Label1" runat="server"  Text='<%# Eval("id") %>' ></asp:Label>
<br />
title:<asp:Label ID="Label2" runat="server"  Text='<%# Eval("title") %>' ></asp:Label>
<br />
summary:<asp:Label ID="Label3" runat="server"  Text='<%# Eval("summary") %>' ></asp:Label>
<br />
article:<br />
<asp:TextBox ID="TextBox1" runat="server" Text='<%# Eval("article") %>' Height="150px" TextMode="MultiLine" Width="214px"></asp:TextBox>
</ItemTemplate>
</asp:FormView>

 

後端程式碼:(用dataReader去資料庫抓資料)

protected void Page_Load(object sender, EventArgs e)
{
SqlConnection Conn = new SqlConnection(WebConfigurationManager.ConnectionStrings["testConnectionString"].ConnectionString);

SqlCommand cmd = new SqlCommand("select id,title,summary,article from test", Conn);

SqlDataReader dr = null;

try
{
Conn.Open();
dr = cmd.ExecuteReader();
FormView1.DataSource = dr;
FormView1.DataBind();
}
catch (Exception ex)
{
Response.Write(ex.ToString());
}
finally
{
if (dr == null)
{
cmd.Cancel();
}
if (Conn.State == ConnectionState.Open)
{
Conn.Close();
Conn.Dispose();
}
}
}

arrow
arrow
    全站熱搜
    創作者介紹
    創作者 melomelo1988 的頭像
    melomelo1988

    melo 唐

    melomelo1988 發表在 痞客邦 留言(0) 人氣()