Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Wanet Telecoms Ltd on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Now, how to return that bound textbox to the code behind for updating? 1

Status
Not open for further replies.

belle9

Programmer
Nov 3, 2004
87
US
Now that I got the textbox to display the multiple rows from the DB, I need to return it back to the db for updating. How do I pass each item of the datalist to the stored proc?

Code:
  myCommand = New SqlCommand("admin_UpdateDiet", oConn)
        myCommand.CommandType = CommandType.StoredProcedure

        myCommand.Parameters.Add(New SqlParameter("@AID", SqlDbType.Int))
        myCommand.Parameters("@AID").Value = AID

   myCommand.Parameters.Add(New SqlParameter("@Data", SqlDbType.Int))
        myCommand.Parameters("@Data").Value = ??????

Thanks guys!
 
are you in the EditItem sub?

if so...you do a FindControl on it...

dim t as textbox
t = CType(e.Item.FindControl("TextBoxName"), TextBox)

myCommand.Parameters("@data").Value= t.text

"...we both know I'm training to become a cagefighter...see what happens if you try 'n hit me..."
 
Any suggestion if I'm not in the editItem sub? Preferrably I'd want to do it in the Page Load....
 
here's a sample that i have in a datalist...take a look at it...I use 1 button to update an entire datalist...with 1 textbox...

Code:
  Private Sub updateRecord()
    Dim i As Integer = 0
    Dim chargeAcid As Integer
    Dim txt As TextBox
    Dim du As New VKPBDataLayer.DataUpdater
    Dim pJobID As SqlParameter = New SqlParameter("@jobid", CInt(Request.QueryString("jobid")))
    Dim pChgID As SqlParameter = New SqlParameter("@chgID", SqlDbType.Int)
    Dim pHours As SqlParameter = New SqlParameter("@hours", SqlDbType.Decimal)
    Dim pID As SqlParameter = New SqlParameter("@id", CInt(Me.lblID.Text))
    Dim pRef As SqlParameter = New SqlParameter("@ref", "Ref")
    Dim pRate As SqlParameter = New SqlParameter("@rate", CDec(Me.txtRate.Text))
    Dim cmd As SqlCommand = New SqlCommand("VKPB_SPSaveHours")
    cmd.CommandType = CommandType.StoredProcedure

    Try
      Do While i < Me.dtCharges.Items.Count
        cmd.Parameters.Clear()
        pChgID.Value = Me.dtCharges.DataKeys(i)
        txt = CType(Me.dtCharges.Items(i).FindControl("txtHours"), TextBox)
        If IsNumeric(txt.Text) = True Then
          pHours.Value = CInt(txt.Text)
        Else
          pHours.Value = 0
        End If
        cmd.Parameters.Add(pJobID)
        cmd.Parameters.Add(pChgID)
        cmd.Parameters.Add(pHours)
        cmd.Parameters.Add(pID)
        cmd.Parameters.Add(pRef)
        cmd.Parameters.Add(pRate)

        du.returnUpdateStatus(cmd)
        i = i + 1
      Loop

      Me.lblMessage.Text = "Record updated."
      Me.lblMessage.Visible = True
      Me.loadStaff(CInt(Request.QueryString("jobid")))
      Me.loadChargeGrid()
      Me.loadDetails(CInt(Request.QueryString("jobid")))
      Me.txtChanged.Text = "0"
    Catch ex As Exception
      Dim a As New VKPBDataLayer.CaughtError
      a.showMeTheError(ex)
      a = Nothing
    End Try
  End Sub

"...we both know I'm training to become a cagefighter...see what happens if you try 'n hit me..."
 
Ok, this looks good to get me started. A question:

Can I give a textbox a CommandArgument, or some way of passing back the ID of the item that's being changed? Or can I use a hidden label?

Thanks again.
 
Never mind, I'm using a hidden label. This works perfectly, thanks Checkai.
 
Ok, another question:

I'd like to vary the Text in my textbox, depending on where in the program you are...If it's the first time coming to the page, I'd like to grab the value from the database, but once that's there, i need to allow the user to update the field. Right now it updates the db with the value that it grabbed from the db, nothing more..what am I missing?

Code:
<asp:datalist id="dlDiet" runat="server" Width="325" Height="212">							    <ItemTemplate>
	<asp:TextBox id="txtDiet2" Text='<%#DataBinder.Eval(Container.DataItem,"Data")%>' Width="301px" Runat="server" Visible="True">
	</asp:TextBox>
    </ItemTemplate>
</asp:datalist>

Code behind:
Code:
  dtxt = CType(Me.dlDiet.Items(i).FindControl("txtDiet2"), TextBox)
 
the code that i gave you is a sample to loop through each text box and update it in the db...

for instance, that code is under a button click for me...

"...we both know I'm training to become a cagefighter...see what happens if you try 'n hit me..."
 
I may know what the problem is:

Code:
Dim du As New VKPBDataLayer.DataUpdater
what is VKPBDataLayer?


I'm missing du, which is probably why my data is not getting updated....

What I have (i left the declarations out):

Code:
 Do While i < Me.dlDiet.Items.Count
                myCommand.Parameters.Clear()
                dlabel = CType(Me.dlDiet.Items(i).FindControl("lblDietID"), Label)
                If (dlabel.Text) <> "" Then
                    dietId.Value = CInt(dlabel.Text)
                Else
                    dietId.Value = 0
                End If

                dtxt = CType(Me.dlDiet.Items(i).FindControl("txtDiet2"), TextBox)

                If dtxt.Text <> "" Then
                    dietData.Value = dtxt.Text
                Else
                    i = i + 1
                    GoTo EndOfLoop

                End If
                myCommand.Parameters.Add(dietId)
                myCommand.Parameters.Add(dietData)
                i = i + 1

                myCommand.Parameters.Add(New SqlParameter("RETURN VALUE", SqlDbType.Int))
                myCommand.Parameters("RETURN VALUE").Direction = ParameterDirection.ReturnValue

                RV = myCommand.Parameters("RETURN VALUE").Value

                myCommand.ExecuteNonQuery()

EndOfLoop:  Loop
        Catch ex As Exception

        End Try
 
that is a class that updates my database....
I'll send it to you..

Code:
Namespace VKPBDataLayer
Public Class DataUpdater
    Dim objconn As starDB

    Public Function returnUpdateStatus(ByVal c As SqlClient.SqlCommand) As Boolean
      Dim status As Integer

      Try
        objconn = New starDB
        c.Connection = objconn.starDB
        objconn.open()
        status = c.ExecuteNonQuery()

        If status = 1 Then Return False Else Return True

      Catch objException As Exception
        Dim fp As New VKPBDataLayer.CaughtError
        fp.showMeTheError(objException)
        fp = Nothing
        Return False
      Finally
        If objconn.starDB.State <> ConnectionState.Closed Then
          objconn.close()
        End If
        If Not (objconn Is Nothing) Then
          objconn.Dispose()
        End If
        objconn = Nothing
      End Try
    End Function

  End Class
End Namespace

"...we both know I'm training to become a cagefighter...see what happens if you try 'n hit me..."
 
Does a class have to reside anywhere specific, or can I stick it in in my current file? I suspect this is a silly newbie question, and I apologize...

I converted what you have to my format, the only thing I'm missing is what CaughtError is, I get that its undefined.

Code:
Namespace VKPBDataLayer
    Public Class DataUpdater
        Public Function returnUpdateStatus(ByVal c As SqlClient.SqlCommand) As Boolean
            Dim status As Integer
            Dim conString As String = ConfigurationSettings.AppSettings("constring")
            Dim myConnection As SqlConnection = New SqlConnection(conString)
            Dim myCommand As SqlCommand
            Dim myReader As SqlDataReader
            Dim myParam As SqlParameter

            Try

                myconnection.open()
                status = c.ExecuteNonQuery()

                If status = 1 Then Return False Else Return True

            Catch objException As Exception
                Dim fp As New VKPBDataLayer.CaughtError
                fp.showMeTheError(objException)
                fp = Nothing
                Return False
            Finally
                If myConnection.State <> ConnectionState.Closed Then
                    myConnection.Close()
                End If
                If Not (myConnection Is Nothing) Then
                    myConnection.Dispose()
                End If
                myConnection = Nothing
            End Try
        End Function

    End Class
End Namespace
 
I think I'm getting sidetracked...With using your VKPBDataLayer db updater I'd still have the problem of grabbing what the user entered, wouldn't I, if I hardcode the text of the textbox to be the db item?
 
Lets retrace what you've got
Datalist with Textbox loaded on page load?
an update button that updates the db with text box values?
post your pages code

"...we both know I'm training to become a cagefighter...see what happens if you try 'n hit me..."
 
ok, here goes.
Datalist with Textbox loaded on page load and update button that updates the db with text box values:
Code:
<tr>
												<td></td>
												<td><asp:datalist id="dlDiet" runat="server" Width="325" Height="212">
														<ItemTemplate>
															<asp:TextBox id="txtDiet2" Text='<%#DataBinder.Eval(Container.DataItem,"Data")%>' Width="301px" Runat="server" Visible="True">
															</asp:TextBox>
															<asp:Label id="lblDietID" runat="server" Visible="True" text='<%#DataBinder.Eval(Container.DataItem,"DietID")%>'>
															</asp:Label>
														</ItemTemplate>
													</asp:datalist></td>
											</tr>
											<TR>
												<TD align="center" colSpan="3"><asp:button id="btnUpdateDiet" runat="server" CssClass="formButton" Text="Update"></asp:button>&nbsp;
													<asp:button id="btnDeleteDiet" runat="server" CssClass="formButton" Text="Delete"></asp:button></TD>
											</TR>

Code behind:
Code:
 Private Sub btnUpdateDiet_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnUpdateDiet.Click


        myConnection.Open()
        myCommand = New SqlCommand("admin_UpdateDiet", myConnection)
        myCommand.CommandType = CommandType.StoredProcedure

        myCommand.Parameters.Add(New SqlParameter("@AID", SqlDbType.Int))
        myCommand.Parameters("@AID").Value = Session("AthleteID")


        Dim dietId As SqlParameter = New SqlParameter("@dietID", SqlDbType.Int)
        Dim dietData As SqlParameter = New SqlParameter("@data", SqlDbType.VarChar, 2500)

        Dim i As Integer = 0
        Dim dlabel As Label
        Dim dtxt As TextBox
        Dim RV As Integer

        Try
            Do While i < Me.dlDiet.Items.Count
                myCommand.Parameters.Clear()
                dlabel = CType(Me.dlDiet.Items(i).FindControl("lblDietID"), Label)
                If (dlabel.Text) <> "" Then
                    dietId.Value = CInt(dlabel.Text)
                Else
                    dietId.Value = 0
                End If

                dtxt = CType(Me.dlDiet.Items(i).FindControl("txtDiet2"), TextBox)

                If dtxt.Text <> "" Then
                    dietData.Value = dtxt.Text
                Else
                    i = i + 1
                    GoTo EndOfLoop

                End If
                myCommand.Parameters.Add(dietId)
                myCommand.Parameters.Add(dietData)

                myCommand.Parameters.Add(New SqlParameter("RETURN VALUE", SqlDbType.Int))
                myCommand.Parameters("RETURN VALUE").Direction = ParameterDirection.ReturnValue

                RV = myCommand.Parameters("RETURN VALUE").Value

                i = i + 1

                myCommand.ExecuteNonQuery()

EndOfLoop:  Loop

        Catch ex As Exception

        End Try



        If RV = "0" Then
            lblMsg.Text = "<font color=red>Diet has been updated!<br></font>"
        Else
            lblMsg.Text = "<font color=red>Error updating diet</font>"
        End If

        myConnection.Close()

    End Sub
 
tell me that your page load has this in it...

Code:
if not page.isPostback then
  'Load the datalist
end if

if it doesn't have this, then what it is basically doing is loading the datalist on page load, then when you click the update button, it loads the datalist from the db and updates...so all of your values are lost...what you want is a sub to do the loading of your datalist...

Code:
if not page.isPostback then
  me.loadList()
end if

private Sub loadList
  'Load datalist
End Sub

'Call this on button click
private sub updateList
   'do update stuff...
   'After update stuff if you're staying on the same page
   me.loadList
End Sub


"...we both know I'm training to become a cagefighter...see what happens if you try 'n hit me..."
 
you are welcome...the postback thing is something that a lot of people miss, when they're first starting out.

"...we both know I'm training to become a cagefighter...see what happens if you try 'n hit me..."
 
Antoher approache is to always bind your data in the Page_Prerender. This is easier to manager. This way if your changing the data based upon multiple changes your making in button_click events or other controls, the Page_Prerender is the last thing that occurs before the page is sent to client browser. As you start adding more functionality to an aspx page and still doing everything in pageload it starts looking more like the old unmanaged classic asp 3.0 rather than asp.net.

 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top