继续从上面的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)
using System;
using System.Data;
using System.Web;
using System.Web.UI.WebControls;
using umbraco.cms.businesslogic.datatype;
using umbraco.editorControls.userControlGrapper;
using Microsoft.ApplicationBlocks.Data; namespace UmbracoCreateCustomDatatypeWithWrapper
{
public class Demo : UserControl, IUsercontrolDataEditor
{
[DataEditorSetting("Connection string")]
public string ConnectionString { get; set; } [DataEditorSetting("Select statement")]
public string SelectStatement { get; set; } [DataEditorSetting("Text column")]
public string TextColumn { get; set; } [DataEditorSetting("Value column")]
public string ValueColumn { get; set; } public string umbracoValue; protected void Page_Load(object sender, EventArgs e)
{
if (Page.IsPostBack)
{
//onsave
value = control.SelectedValue;
}
else
{
control.DataSource = SqlHelper.ExecuteReader(
ConnectionString,
CommandType.Text,
SelectStatement);
control.DataTextField = TextColumn;
control.DataValueField = ValueColumn;
control.DataBind();
control.Items.Insert(, new ListItem(String.Empty, String.Empty)); control.SelectedIndex = ;
if (value != null)
control.SelectedValue = value.ToString();
}
} public object value
{
get
{
return umbracoValue;
}
set
{
umbracoValue = value.ToString();
}
}
}
}
如下使用
显示效果
这样是不是更好一点呢。