close

並不是每一個Web控制項都可以DataBinding Expression,所以就必須用一些特殊方式來達成目的。

如果控制項有DataSourceID以及DataMember這兩個屬性,那可以直接使用DataBinding Expression。

(通常只有大型控制項有,小型控制項如:textbox,lable...是沒有的)

 

所以小型控制項想DataBinding Expression呈現資料該怎麼辦?

1.

我們可以借助大型控制項的力量,因為大型控制項有DataSourceID以及DataMember這兩個屬性,

所以我們將大型控制項轉成樣板模式,然後加入textbox...一樣可以使用DataBinding Expression。

 

2.

使用副程式。

 

前端程式碼如下:(拉入一個Label以及DropDownList)

<form id="form1" runat="server">
<div>
<!-- 這裡呼叫副程式--!>
<asp:Label ID="Label1" runat="server" Text="<% #DBInit() %>" ></asp:Label>
<br />
<asp:DropDownList ID="DropDownList1" runat="server" DataSource="<% #DBInit() %>" DataTextField="title" DataValueField="id" >
</asp:DropDownList>

</div>
</form>

 

後端程式碼:(使用DataSet or DataReader皆可)

protected void Page_Load(object sender, EventArgs e)
{

//這裡使整個頁面的控制項純新DataBinding一次
Page.DataBind();
}

//副程式去資料庫中撈資料

public DataSet DBInit()
{
SqlConnection Conn = new SqlConnection(WebConfigurationManager.ConnectionStrings["testConnectionString"].ConnectionString);
SqlDataAdapter myAdapter = new SqlDataAdapter("select top 10 id,title from test", Conn);
DataSet ds = new DataSet();
myAdapter.Fill(ds, "test");
return ds;
}

另外可以看見Label 跟 DropDownList 使用副程式DataBinding Expression的結果,我認為最好還是乖乖的放在樣板內用吧!

DataBindingExpression

重點:

為何大型控制項不用Page.DataBind()? 但是Page需要?

因為大型控制項在PreRender事件(在Control物件載入之前,到呈現到畫面之前發生)期間會自動解析DataBinding Expression。

 

 

 

 

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

    melo 唐

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