继续从上面的Data Types的自定义控件说起。前面用到了自定义控件的数据绑定,虽然这使得我们可以调用外部数据了,但这似乎还比较死板,如果再调用其他数据,还得再创建一个控件,那样的话就会出现类似的功能性控件,复用率不高,而且维护起来也不方便,其实有更好的方法实现,
看下面的代码
.ascx file:
<%@ Control Language="C#" AutoEventWireup="true" CodeBehind="Demo.ascx.cs" Inherits="UmbracoCreateCustomDatatypeWithWrapper.Demo" %>
<asp:DropDownList ID="control" runat="server"> </asp:DropDownList>
.ascx.cs file (code behind)
1 using System; 2 using System.Data; 3 using System.Web; 4 using System.Web.UI.WebControls; 5 using umbraco.cms.businesslogic.datatype; 6 using umbraco.editorControls.userControlGrapper; 7 using Microsoft.ApplicationBlocks.Data; 8 9 namespace UmbracoCreateCustomDatatypeWithWrapper 10 { 11 public class Demo : UserControl, IUsercontrolDataEditor 12 { 13 [DataEditorSetting("Connection string")] 14 public string ConnectionString { get; set; } 15 16 [DataEditorSetting("Select statement")] 17 public string SelectStatement { get; set; } 18 19 [DataEditorSetting("Text column")] 20 public string TextColumn { get; set; } 21 22 [DataEditorSetting("Value column")] 23 public string ValueColumn { get; set; } 24 25 public string umbracoValue; 26 27 protected void Page_Load(object sender, EventArgs e) 28 { 29 if (Page.IsPostBack) 30 { 31 //onsave 32 value = control.SelectedValue; 33 } 34 else 35 { 36 control.DataSource = SqlHelper.ExecuteReader( 37 ConnectionString, 38 CommandType.Text, 39 SelectStatement); 40 control.DataTextField = TextColumn; 41 control.DataValueField = ValueColumn; 42 control.DataBind(); 43 control.Items.Insert(0, new ListItem(String.Empty, String.Empty)); 44 45 control.SelectedIndex = 0; 46 if (value != null) 47 control.SelectedValue = value.ToString(); 48 } 49 } 50 51 public object value 52 { 53 get 54 { 55 return umbracoValue; 56 } 57 set 58 { 59 umbracoValue = value.ToString(); 60 } 61 } 62 } 63 }
如下使用
显示效果
这样是不是更好一点呢。