asp.net VB Findcontrol无法在formview之外找到控件

时间:2013-12-12 00:36:45

标签: asp.net vb.net dotnetnuke formview findcontrol

我正在创建一个包含formview的DNN页面。 sqldatasource位于formview的外部。我需要从代码隐藏控制sqldatasource.insert()调用。 (有2个按钮 - 1个插入并转到一个页面,1个插入并将formview更改为编辑模式以添加其他数据)。

代码隐藏无法在formview之外找到控件。我将粘贴代码和前端sqldatasource(formview非常复杂和冗长)。

我正在使用递归的findcontrol。我开始查看me.page级别(顶级?),但我仍然得到对sql数据源的空引用。 (找不到) (代码工作时我只是常规命令=插入按钮,但我需要控制重定向,具体取决于按下哪个按钮)

任何想法???

前端SQL数据源:

 <asp:SqlDataSource ID="PromotionSqlDataSource" runat="server" 
        ConnectionString="<%$ ConnectionStrings%>" 
        InsertCommand="INSERT code is here" 
        SelectCommand="select code is here" 
        UpdateCommand="UPDATE code is here" 
        DeleteCommand="DELETE code is here">
        <InsertParameters>
            lots of parameters
        </InsertParameters>
        <EditParameters>
            lots of parameters
        </EditParameters>

        <DeleteParameters>
        </DeleteParameters>

 </asp:SqlDataSource>

的FormView:

  <asp:FormView ID="FormView1" runat="server" AllowPaging="True" 
        DataKeyNames="Promo_ID" 
        DataSourceID="PromotionSqlDataSource" DefaultMode="Insert">

        Lots of form code here
<asp:Button ID="Button6" runat="server"  Text="Next"  onclick="Button6_Click"  />
    </asp:FormView>

代码背后:

Protected Sub Button6_Click(sender As Object, e As System.EventArgs)
    MessageBox("BUTTON 6 CLICK")

    Dim PromotionSqlDataSource As SqlDataSource = TryCast(FindControlRecursive(Me.Page, "PromotionSqlDataSource"), SqlDataSource)
    PromotionSqlDataSource.Insert()
    FormView1.ChangeMode(FormViewMode.Edit)
End Sub

Public Function FindControlRecursive(root As Control, id As String) As Control
    If root.ID = id Then
        Return root
    End If

    Return root.Controls.Cast(Of Control)().[Select](Function(c) FindControlRecursive(c, id)).FirstOrDefault(Function(c) c IsNot Nothing)
End Function

2 个答案:

答案 0 :(得分:0)

我认为您可以在不使用PromotionSqlDataSource的情况下使用FindControl。 请尝试以下。

Protected Sub Button6_Click(sender As Object, e As System.EventArgs)
    MessageBox("BUTTON 6 CLICK")

    'Dim PromotionSqlDataSource As SqlDataSource = TryCast(FindControlRecursive(Me.Page, "PromotionSqlDataSource"), SqlDataSource)
    PromotionSqlDataSource.Insert()
    FormView1.ChangeMode(FormViewMode.Edit)
End Sub

答案 1 :(得分:0)

只需跟进我必须采取的措施来解决此问题。这必然是MS Visual Studio编译代码的方式中的一个错误。它应该使用上面的代码,但它从来没有。我将每个按钮设为CommandName =“Insert”按钮。基础asp.net代码的工作方式是它触发button_click代码,然后是sqldataserver插入代码。

我创建了一个全局标志,使用每个按钮的onClick事件设置。在sqldatasource的after_Inserted事件中,我读取了标志以确定单击了哪个按钮。我在after Inserted事件中有一个if then else语句,它根据标志的设置方式重定向页面。

不优雅,但它正是我希望它的工作方式。