2

这里创建自定义控件是第一个控件代码

1. StartScreen.cs 和 ActDesc.cs 控件。

  1. 第一次加载页面时,我看到两个编辑按钮。
  2. 我单击其中任何一个,查看其中包含内容的文本框。
  3. 然后我点击保存保存按钮事件不会被触发。
  4. 在我看来,在初始 CreateChildControls 期间创建的控件会触发该事件。在 Postback 上创建的不会触发事件。
  5. 我在编辑按钮的 Command 事件处理程序上调用 ControlsCreate() 方法。我也尝试过使用 EnsureChildControls() 调用。还是没用?

谁能指导我实现这一目标的方法?

. .

public class Wrapper
{
    public string Name { get; set; }
    public string Description { get; set; }
}
namespace Cons
{
    public class StartScreen : CompositeControl
    {
        public StartScreen()
        {
            //
            // TODO: Add constructor logic here
            //
        }
        protected override void CreateChildControls()
        {
            List<Wrapper> list = new List<Wrapper>();
            for (int i = 0; i < 2; i++)
            {
                list.Add(new Wrapper { Name = "D", Description = "DDDDDDDDDD" });
            }
            ActDesc desc = new ActDesc(list);
            desc.DataBind();
            this.Controls.Add(desc);
            base.CreateChildControls();
        }
    }
}

public class ActDesc : CompositeControl
{
    IEnumerable<Wrapper> list = new Wrapper[] { };
    public ActDesc(IEnumerable<Wrapper> list)
    {
        this.list = list;
    }
    private void ControlsCreate()
    {
        this.Controls.Clear();
        Table activityDescription = new Table();
        int i = 1;
        foreach (var item in list)
        {
            TableRow tempRow = new TableRow();
            TableCell tempLeftCell = new TableCell();
            tempLeftCell.Text = item.Name;

            TableCell tempRightCell = new TableCell();
            tempRightCell.HorizontalAlign = HorizontalAlign.Right;

            if (EditId == 0)
            {
                ImageButton editButton = new ImageButton();
                editButton.ID = string.Format("editButton_{0}", i);
                editButton.ImageUrl = "add_16.png";
                editButton.CommandArgument = i.ToString();
                editButton.Command += new CommandEventHandler(editButton_Command);
                editButton.CommandName = "Edit";

                tempRightCell.Controls.Add(editButton);
            }
            else
            {
                if (EditId == i)
                {
                    ImageButton saveButton = new ImageButton();
                    saveButton.ID = string.Format("saveButton_{0}", i);
                    saveButton.ImageUrl = "~/save.png";
                    saveButton.CommandArgument = i.ToString();
                    saveButton.Command += new CommandEventHandler(editButton_Command);
                    saveButton.CommandName = "Save";

                    tempRightCell.Controls.Add(saveButton);
                }
            }

            tempRow.Cells.Add(tempLeftCell);
            tempRow.Cells.Add(tempRightCell);

            //Add the first row which contains the header name and the edit button if AllowEdit is true
            activityDescription.Rows.Add(tempRow);

            tempRow = new TableRow();

            tempLeftCell = new TableCell();
            tempLeftCell.ColumnSpan = 2;

            Control tempControl;
            if (EditId > 0 && EditId.Equals(i))
            {
                TextBox txt = new TextBox();
                txt.TextMode = TextBoxMode.MultiLine;
                txt.ID = "txt" + i;
                txt.Text = item.Description;
                tempControl = txt;
            }
            else
            {
                Literal litContent = new Literal();
                litContent.ID = string.Format("literalContent_{0}", i);
                litContent.Mode = LiteralMode.Transform;
                litContent.Text = item.Description;

                tempControl = litContent;
            }

            tempLeftCell.Controls.Add(tempControl);
            tempRow.Cells.Add(tempLeftCell);

            // Add the second row which shows the detailed HTML description..
            activityDescription.Rows.Add(tempRow);
            i = i + 1;
        }
        this.Controls.Add(activityDescription);
    }
    protected override void CreateChildControls()
    {
        ControlsCreate();
        base.CreateChildControls();
    }

    void editButton_Command(object sender, CommandEventArgs e)
    {
        switch (e.CommandName)
        {
            case "Edit":
                string id = e.CommandArgument.ToString();
                EditId = Convert.ToInt32(id);
                ControlsCreate();
                break;
            default:
                break;
        }
    }
    public int EditId
    {
        set
        {
            this.ViewState["__EditId"] = value;
        }
        get
        {
            return Convert.ToInt32(this.ViewState["__EditId"]);
        }
    }
    public bool AllowEdit { get; set; }
}
4

2 回答 2

0

我确实找到了我的问题的答案,问题是我认为我没有为其分配 ID 的控件可能使用不同的 ID 重新创建,因此与以前回发期间保存的值不匹配。我还更改了回发处理程序中的代码以调用 EnsureChildControls,同时设置 this.ChildControlsCreated=false 并因此重新创建子控件。

于 2013-04-04T07:23:53.480 回答
0

要使控件具有事件,您必须使用事件声明它。这是在 vb.net 但可以在这里转换:http: //converter.telerik.com/。这也继承自 scriptcontrol 而不是复合,但它应该工作相同:

<Assembly: WebResource("myProject.FileUpload.css", "text/css", PerformSubstitution:=True)> 
< _
ToolboxData("<{0}:FileUpload ID='FileUpload{0}'  runat=""server""> </{0}:FileUpload>"), _
ClientCssResource("myProject.FileUpload.css")> _
Public Class FileUpload
    Inherits ScriptControl
    Implements INamingContainer, IPostBackEventHandler

    Private WithEvents btnMyButton As New Button

   .... 

    Protected Overrides Sub CreateChildControls()
        'method to create my controls
        createDynamicControls()

        'if you are using update panels and wish to do an async 
        ' post back, you must first register the conrol with 
        ' the pages script manager.  If you are not using update panels, you can
        ' skip this
        ScriptManager.GetCurrent(Page).RegisterAsyncPostBackControl(Me.btnMyButton)      

        MyBase.CreateChildControls()
    End Sub

   Protected Overrides Function SaveViewState() As Object
        Return New Pair(MyBase.SaveViewState(), Nothing)
    End Function


    Protected Overrides Sub LoadViewState(ByVal savedState As Object)
        MyBase.LoadViewState(CType(savedState, Pair).First)
        EnsureChildControls()
    End Sub

     Protected Overrides Sub OnInit(ByVal e As System.EventArgs)
        attachWebResources()
        MyBase.OnInit(e)

    End Sub

    Protected Overrides Sub OnLoad(ByVal e As System.EventArgs)
        MyBase.OnLoad(e)
    End Sub

     Private Sub attachWebResources()
        'use this to attach an embedded CSS file with the DLL
        Dim styleLink As String = "<link rel='stylesheet' text='text/css' href='{0}' />"
        Dim location As String = Page.ClientScript.GetWebResourceUrl(Me.[GetType](), "myProject.FileUpload.css")
        Dim styleInclude As New LiteralControl([String].Format(styleLink, location))
        DirectCast(Page.Header, HtmlControls.HtmlHead).Controls.Add(styleInclude)
    End Sub

     Protected Sub btnMyButton _click(ByVal sender As Object, ByVal e As EventArgs) Handles btnMyButton .Click

      '....do stuff
    end sub
        Public Sub RaisePostBackEvent(ByVal eventArgument As String) Implements System.Web.UI.IPostBackEventHandler.RaisePostBackEvent
          'required for IPostBackEventHandler
    End Sub

  Private Sub createDynamicControls()
     controls.Clear()
     'instantiate your control here and add it to the controls object
  end sub
end Class

让我知道这是否有帮助,或者您是否被困在某个地方。

于 2013-03-27T10:58:22.093 回答