i have a datalist in which data from table detail are displayed and it is working fine. now i need to insert some data of this datalist to another table detail2. i give a save button to each raw of the datalist so that on click of this save button particular data of that raw store to table detail2. bellow the design of my datalist .
<asp:DataList ID="drecord" runat="server" Font-Bold="false" Font-Names="times new roman" Font-Size="Small" DataKeyField="id" RepeatColumns="1">
<ItemTemplate>
<div><table>
<tr><td><asp:ImageButton ID="ImageButton1" runat="server" ImageUrl='<%# GetImageURL(Eval("Pic")) %>' PostBackUrl='<%# Eval("id", "qrystng.aspx?id={0}") %>'/><br />
<asp:LinkButton ID="Name1" runat="server" ForeColor="Blue" Text='<%#Container.DataItem("Name")%>'><br />
</asp:LinkButton><asp:Label ID="id" runat="server" Text='<%#Container.DataItem("id")%>'></asp:Label></td>
<td><asp:Button ID="insert" runat="server" BorderStyle="None" Font-Bold="true" Text="save" OnClick="saveinsert_click"/></td></tr>
</table></div>
</ItemTemplate>
</asp:DataList>
and this onclick event saveinsert is for inserting data to table detail2.
Sub saveinsert(ByVal sender As Object, ByVal e As System.EventArgs)
Dim cmd As New SqlCommand("insert into detail2(serial,id) values('" & fid & "',@rid)", con)
cmd.Parameters.Add("@rid", SqlDbType.VarChar).Value = DirectCast(drecord.Controls(0).FindControl("id"), Label).Text
con.Open()
cmd.ExecuteNonQuery()
con.Close()
End sub
but when i click on the insert button it give errror as "Object reference not set to an instance of an object." Exception Details : System.NullReferenceException: Object reference not set to an instance of an object.
and shows error on this line " cmd.Parameters.Add("@rid", SqlDbType.VarChar).Value = DirectCast(drecord.Controls(0).FindControl("id"), Label).Text "
the datalist displaying records correctly. i need to take the value of label "id" to store . i am not able to catch where i went wrong . help me with this
Use ItemCommand event of datalist:
Protected Sub drecord_ItemCommand(source As Object, e As DataListCommandEventArgs)
If e.CommandName = "CommabdName" Then
Dim Label1 As Label = DirectCast(e.item.FindControl("id"), Label)
Dim labelText As string = Label1.Text
//write your code here
End If
End Sub
<asp:DataList ID="drecord" runat="server" Font-Bold="false" Font-Names="times new roman" Font-Size="Small" DataKeyField="id" RepeatColumns="1">
<ItemTemplate>
...................
<td><asp:Button ID="insert" CommandName="CommabdName" runat="server" BorderStyle="None" Font-Bold="true" Text="save" />
.........................
</ItemTemplate>
</asp:DataList>