这是我的数据主义者:
<asp:DataList ID="DataList1" runat="server" DataSourceID="SqlDataSource1"
RepeatLayout="Flow">
<ItemTemplate>
<asp:Label ID="IdLabel" runat="server" Text='<%# Eval("ID") %>' Visible="False" />
Titre:
<asp:Label ID="TitreLabel" runat="server" Text='<%# Eval("Titre") %>' />
<br />
Description:
<asp:Label ID="DescriptionLabel" runat="server"
Text='<%# Eval("Description") %>' />
<br />
<asp:Image ID="Image1" runat="server"
ImageUrl='<%# Eval("ID", "Handler.ashx?ID={0}") %>' Width="200" Height="200"/>
<br />
comments:
<asp:Label ID="commentsLabel" runat="server" Text='<%# Eval("comments") %>' />
<br />
Ajouter commentaire
<asp:button ID="btnAjouter" runat="server" OnCommand="Button_Command"
CommandName="add" Text="Ajouter" />
<asp:TextBox ID="TextBoxComments" runat="server"></asp:TextBox>
<br/>
<br/>
</ItemTemplate>
</asp:DataList>
这是我的aspx.vb按钮事件:
Sub Button_Command(ByVal sender As Object, ByVal e As CommandEventArgs)
Dim connectionString As String = WebConfigurationManager.ConnectionStrings("BecsEtMuseauxSQL").ConnectionString
Dim con As SqlConnection = New SqlConnection(connectionString)
con.Open()
Dim cmd As New SqlCommand("updateComments", con)
cmd.CommandType = CommandType.StoredProcedure
//I try this ....
cmd.Parameters.Add("@id", SqlDbType.Int).Value = DataList1.FindControl("IdLabel").ToString()
cmd.Parameters.Add("@Comments", SqlDbType.NVarChar).Value = DataList1.FindControl("TextBoxComments").ToString()
cmd.ExecuteNonQuery()
End Sub
我收到如下错误:“对象引用未定义为对象实例”
在这种情况下,如何从标签IdLabel和TextBoxComments中捕获值?
答案 0 :(得分:1)
你应该处理DataList's ItemCommand而不是Button的命令。
然后,您可以使用e.Item.FindControl
找到您的控件:
Private Sub DataList1_ItemCommand(source As Object, e As System.Web.UI.WebControls.DataListCommandEventArgs) _
Handles DataList1.ItemCommand
If e.CommandName = "add" Then
Dim IdLabel = DirectCast(e.Item.FindControl("IdLabel"), Label)
Dim TextBoxComments = DirectCast(e.Item.FindControl("TextBoxComments"), TextBox)
' ... '
End If
End Sub
在aspx上,删除多余的Command
- 处理程序:
<asp:button ID="btnAjouter" CommandName="add" Text="Ajouter" runat="server" />
如果你想使用Button的Click-Event,那也是可能的。
Protected Sub btnAjouter_Click(sender As Object, e As EventArgs)
Dim container = DirectCast(DirectCast(sender, Control).NamingContainer, DataListItem)
Dim IdLabel = DirectCast(container.FindControl("IdLabel"), Label)
Dim TextBoxComments = DirectCast(container.FindControl("TextBoxComments"), TextBox)
' ... '
End Sub
在aspx上,将click-event处理程序添加到按钮:
<asp:button ID="btnAjouter" OnClick="btnAjouter_Click" Text="Ajouter" runat="server" />