1

ホスト ページから動的に読み込まれたユーザー コントロールのボタン クリック イベントを処理しようとしています。私の関連コードは以下に掲載されています。私は正しい道を進んでいると思いますが、この機能を適切に行うには他に何が必要ですか? 現在、「ターゲット メソッドへのバインディング エラー」というメッセージが表示されます。ユーザーコントロールを作成しようとすると。ご協力いただきありがとうございます。

aspx

<asp:UpdatePanel ID="upLeadComm" runat="server" UpdateMode="Conditional">
    <ContentTemplate>
        <asp:PlaceHolder ID="phComm" runat="server"></asp:PlaceHolder>
    </ContentTemplate>
</asp:UpdatePanel>

aspx.cs

else if (e.CommandName == "GetComm")
{
    string[] cplArg = e.CommandArgument.ToString().Split('§');

    UserControl ucLeadComm = (UserControl)LoadControl("Controls/Comments.ascx");

    // Set the Usercontrol Type 
    Type ucType = ucLeadComm.GetType();

    // Get access to the property 
    PropertyInfo ucPropLeadID = ucType.GetProperty("LeadID");
    PropertyInfo ucPropLeadType = ucType.GetProperty("LeadType");

    EventInfo ucEventInfo = ucType.GetEvent("BtnCommClick");
    MethodInfo ucMethInfo = ucType.GetMethod("btnComm_Click");
    Delegate handler = Delegate.CreateDelegate(ucEventInfo.EventHandlerType, ucType, ucMethInfo);
    ucEventInfo.AddEventHandler(ucType, handler);

    // Set the property 
    ucPropLeadID.SetValue(ucLeadComm, Convert.ToInt32(cplArg[0]), null);
    ucPropLeadType.SetValue(ucLeadComm, cplArg[1], null);

    phComm.Controls.Add(ucLeadComm);

   upLeadComm.Update();
}

ascx.cs

public int LeadID { get; set; }
public string LeadType { get; set; }
public event EventHandler BtnCommClick;

public void btnComm_Click(object sender, EventArgs e)
{
    BtnCommClick(sender, e);
}
4

1 に答える 1

0

次の行からエラーが発生しています: Delegate handler = Delegate.CreateDelegate(ucEventInfo.EventHandlerType, ucType, ucMethInfo);

問題はucType、 UserControl のインスタンスを渡す必要がある間に渡すことです。次のようにしてください。

Delegate handler = Delegate.CreateDelegate(ucEventInfo.EventHandlerType, ucLeadComm, ucMethInfo);

ucLeadCommを使用したことがないため、それがUserControl のインスタンスであるかどうかはわかりません。使用しLoadControl()ていない場合は、Activator.CreateInstance();または使用GetContructor()Invoke()て、オブジェクトのインスタンスを作成します。

編集1:

返信ありがとうございます。「オブジェクトがターゲット タイプと一致しません」というメッセージが表示されるようになりました。次の行: ucEventInfo.AddEventHandler(ucType, handler);

UserControlまた、その行では、代わりにyour のインスタンスを渡す必要がありますucType

編集2:

助けてくれてありがとう!プロジェクトがビルドされ、エラーはスローされません。ただし、これを aspx ページ内のメソッドに結び付けて、ボタンがクリックされたときに実際に何かを行うにはどうすればよいでしょうか?

この場合、私が理解している場合は、aspx.csにメソッドを作成する必要があります:

public void btnComm_Click(object sender, EventArgs e)
{
   //Here what you want to do in the aspx.cs
}

次に、 aspx.csに含まれる に関連付けられた別のhandlerを作成し、それを に渡します。MethodInfobtnComm_ClickDelegate.CreateDelegate()

MethodInfo ucMethInfo = this.GetType().GetMethod("btnComm_Click");
于 2012-09-13T13:06:04.607 に答える