Link to home
Start Free TrialLog in
Avatar of David Megnin
David MegninFlag for United States of America

asked on

Set the value of a TextBox in a Gridview

I have a simple ASP.Net 4.0 Gridview ID="gv".

The column, "Processed By", DataField="ProcessedBy"

The label, "lblUserName" has the value of the logged in user.

When "Edit" is clicked on a row I need the value of lblUserName to go into "Processed By".

If it's easier to do as a TemplateField, then the TextBox ID will be "txtProcessedBy".
SOLUTION
Avatar of Obadiah Christopher
Obadiah Christopher
Flag of India image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
ASKER CERTIFIED SOLUTION
Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
SOLUTION
Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of David Megnin

ASKER

Here is my gv markup:
                <asp:TemplateField HeaderText="Processed" SortExpression="Processed" ItemStyle-HorizontalAlign="Center">
                    <EditItemTemplate>
                        <asp:CheckBox ID="cbProcessed" runat="server" AutoPostBack="True" Checked='<%# Bind("Processed") %>'
                            OnCheckedChanged="Processed_CheckedChanged" />
                    </EditItemTemplate>
                    <ItemTemplate>
                        <asp:Label ID="lblProcessed" runat="server" Text='<%# Eval("Processed") %>'></asp:Label>
                    </ItemTemplate>

<ItemStyle HorizontalAlign="Center"></ItemStyle>
                </asp:TemplateField>

                <%--<asp:BoundField DataField="ProcessedBy" HeaderText="Processed By" SortExpression="ProcessedBy">
                </asp:BoundField>--%>
                
                <asp:TemplateField HeaderText="ProcessedBy" SortExpression="ProcessedBy">
                    <EditItemTemplate>
                        <asp:TextBox ID="txtProcessedBy" runat="server" Text='<%# Bind("ProcessedBy") %>'></asp:TextBox>
                    </EditItemTemplate>
                    <ItemTemplate>
                        <asp:Label ID="lblProcessedBy" runat="server" Text='<%# Bind("ProcessedBy") %>'></asp:Label>
                    </ItemTemplate>
                </asp:TemplateField>

Open in new window


Here is everything I've tried that hasn't worked.  Most is commented out so it's hard to tell what's what as here are so many failed tries:
Imports System.Data
Imports System.Data.SqlClient
Imports System.Web
Imports System.Web.UI.WebControls

Partial Class wpAdmin
    Inherits System.Web.UI.Page

    Dim iUserName As String = "UserName"
    Dim varFirstName As String
    Dim varLastName As String

    Protected Sub Page_Load(sender As Object, e As System.EventArgs) Handles Me.Load

        'iUserName = Right(Request.ServerVariables("AUTH_USER"), (Request.ServerVariables("AUTH_USER").Length - 5))  ' Remove the five characters: "BETA\"
        iUserName = Request.LogonUserIdentity.Name.Substring(Request.LogonUserIdentity.Name.LastIndexOf("\") + 1)    ' Both of these produce the same UserName minus domain.
        lblUsername.Text = iUserName

    End Sub

    Protected Sub gv_RowCommand(sender As Object, e As System.Web.UI.WebControls.GridViewCommandEventArgs) Handles gv.RowCommand

        ' get the commandargument
        Dim index As Integer = Convert.ToInt32(e.CommandArgument)

        ' Retrieve the row that contains the checkbox checked 
        ' by the user from the Rows collection.
        ' Dim row As GridViewRow = sender.Rows(index)

        ' if label outside of gridview
        'row.Cells(13).Text = Me.lblUsername.Text

        'Dim tb As TextBox = CType(gv.FindControl("txtProcessedBy"), TextBox)
        'tb.Text = Me.lblUsername.Text

        'Dim tb As TextBox = CType(row.FindControl("txtProcessedBy"), TextBox)
        'tb.Text = Me.lblUsername.Text

        'If row.RowState = DataControlRowState.Edit Then
        '    'Dim tb As TextBox = DirectCast(sender.Rows(index).FindControl("txtProcessedBy"), TextBox)
        '    Dim tb As TextBox = CType(gv.FindControl("txtProcessedBy"), TextBox)
        '    tb.Text = Me.lblUsername.Text
        'Else
        '    row.Cells(13).Text = Me.lblUsername.Text
        'End If



        ' if label in the gridview
        ' row.Cells(1).Text = row.Cells(x).Text ' x=column index, first column index=0
    End Sub

    Protected Sub Processed_CheckedChanged(sender As Object, e As System.EventArgs)
        ' change "Anything" to "Update" if you want the gridview to Update the data source, or you can invoke the update later by calling gv.databind()

        Dim CommandEventArgs As New CommandEventArgs("Anything", sender.namingcontainer.DataItemIndex)
        Dim GridViewCommandEventArgs As New GridViewCommandEventArgs(sender, CommandEventArgs)
        gv_RowCommand(gv, GridViewCommandEventArgs)
    End Sub

    'Protected Sub gv_RowDataBound(sender As Object, e As GridViewRowEventArgs)
    '    Dim row As GridViewRow = e.Row


    '    If (row.RowType = DataControlRowType.DataRow) AndAlso ((row.RowState And DataControlRowState.Edit) > 0) Then
    '        Dim txt As TextBox = TryCast(row.FindControl("txtProcessedBy"), TextBox)
    '        ' Do your thing here 
    '        'If txt <> Nothing Then
    '        'End If
    '        txt.Text = Me.lblUsername.Text
    '    End If
    'End Sub




    'Protected Sub cbProcessed_CheckedChanged(sender As Object, e As System.EventArgs)
    '    Dim cbProcessed As CheckBox = DirectCast(sender, CheckBox)
    '    Dim row As GridViewRow = DirectCast(cbProcessed.NamingContainer, GridViewRow)
    '    Dim cid As String = row.Cells(1).Text
    '    Dim status As Boolean = cbProcessed.Checked

    '    Dim query As String = "UPDATE ReturnToWork SET Processed = @Processed, ProcessedBy = @ProcessedBy WHERE CustomerID = @CustomerID"
    '    Dim con As New SqlConnection(ConfigurationManager.ConnectionStrings("WPConnectionString").ConnectionString)
    '    Dim com As New SqlCommand(query, con)

    '    Try
    '        com.Parameters.Add("@Processed", SqlDbType.Bit).Value = status
    '        com.Parameters.Add("@ProcessedBy", SqlDbType.VarChar).Value = iUserName
    '        com.Parameters.Add("@CustomerID", SqlDbType.VarChar).Value = cid

    '        con.Open()
    '        com.ExecuteNonQuery()
    '        con.Close()

    '    Catch ex As Exception
    '        Response.Write(ex)
    '        'Server.Transfer("Error.htm")
    '    End Try
    '    'Response.Redirect(Request.RawUrl)

    'End Sub

    'Protected Sub gv_RowDataBound(sender As Object, e As GridViewRowEventArgs)
    '    If e.Row.RowType = DataControlRowType.DataRow Then
    '        Dim chkbox As CheckBox = TryCast(e.Row.FindControl("cbProcessed"), CheckBox)
    '        'If chkbox Is Not Nothing Then
    '        chkbox.Attributes.Add("OnClick", "javascript:SetValue(this.id);")
    '        'End If
    '    End If
    'End Sub


End Class

Open in new window

I found this which puts the UserName in the TextBox okay, but then it's not saved to the database.  I click Save/Update but the TextBox goes back to being blank.
 ''Protected Sub gv_RowDataBound(sender As Object, e As GridViewRowEventArgs)
    Protected Sub gv_RowDataBound(sender As Object, e As System.Web.UI.WebControls.GridViewRowEventArgs) Handles gv.RowDataBound
        Dim row As GridViewRow = e.Row


        If (row.RowType = DataControlRowType.DataRow) AndAlso ((row.RowState And DataControlRowState.Edit) > 0) Then
            Dim txt As TextBox = TryCast(row.FindControl("txtProcessedBy"), TextBox)
            ' Do your thing here 
            'If txt <> Nothing Then
            'End If
            txt.Text = Me.lblUsername.Text
        End If
    End Sub 

Open in new window


With that Sub commented out, a value typed into the TextBox is saved to the db.
Possible that updateRow is not being triggered, for whatever reason.

txt.Text = Me.lblUsername.Text
gv.UpdateRow(sender.Rows(index), True)

Open in new window

Alan ";0)
Can't access "index" because it is "Friend".  Squiggly under "index".
Hi megnin,
I expect you'll be glad to get this one off your desk!

Protected Sub gv_RowDataBound(sender As Object, e As System.Web.UI.WebControls.GridViewRowEventArgs) Handles gv.RowDataBound
    ' get the commandargument
    Dim index As Integer = Convert.ToInt32(e.CommandArgument)
    
    ' Retrieve the row that contains the checkbox checked 
    ' by the user from the Rows collection.
    Dim row As GridViewRow = sender.Rows(index)

        If (row.RowType = DataControlRowType.DataRow) AndAlso ((row.RowState And DataControlRowState.Edit) > 0) Then
            Dim txt As TextBox = TryCast(row.FindControl("txtProcessedBy"), TextBox)
            ' Do your thing here 
            'If txt <> Nothing Then
            'End If
            txt.Text = Me.lblUsername.Text
        End If
    End Sub 

Open in new window

Alan ";0)
Ha, yeah. ;)

Error      1      'CommandArgument' is not a member of 'System.Web.UI.WebControls.GridViewRowEventArgs'.
If I do it like this, the value goes into the TextBox when user clicks "Edit" but the value is not updated in the database.  WHen user clicks "Save" the TextBox is blank again.

    Protected Sub gv_RowDataBound(sender As Object, e As System.Web.UI.WebControls.GridViewRowEventArgs) Handles gv.RowDataBound
        '    ' get the commandargument
        '    Dim index As Integer = Convert.ToInt32(e.CommandArgument)  ' <---Error

        '    ' Retrieve the row that contains the checkbox checked 
        '    ' by the user from the Rows collection.
        Dim row As GridViewRow = e.Row ' sender.Rows(index)  ' <--- index causes error

        If (row.RowType = DataControlRowType.DataRow) AndAlso ((row.RowState And DataControlRowState.Edit) > 0) Then
            Dim txt As TextBox = TryCast(row.FindControl("txtProcessedBy"), TextBox)
            ' Do your thing here 
            'If txt <> Nothing Then  ' <-- <> causes error
            'End If
            txt.Text = Me.lblUsername.Text
        End If
    End Sub

Open in new window

Hi megnin,

When "Edit" is clicked on a row I need the value of lblUserName to go into "Processed By"

Add a new sub to handle the textbox databinding event:
Protected Sub txtProcessedBy_DataBinding(sender As Object, e As System.EventArgs)
    sender.text = My.User.Name
End Sub

Open in new window


In your gridview attach the event:
<EditItemTemplate>
  <asp:TextBox ID="txtProcessedBy" runat="server" Text='<%# Bind("ProcessedBy") %>' OnDataBinding="txtProcessedBy_DataBinding"></asp:TextBox>
</EditItemTemplate>

Open in new window

Alan ";0)
Thank you very much.  The solution I finally used was very similar.  I learned a lot working on this one.  In Microsoft SQL Server Management Studio, the "Use Optomistic Concurrency" option is not always your friend.