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".
LVL 1
megninAsked:
Who is Participating?
 
CodeCruiserConnect With a Mentor Commented:
Handle the RowEditing event of gridview and use the row index supplied in e parameter to do the FindControl and set the textbox value

http://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.gridview.rowediting.aspx
0
 
Obadiah ChristopherConnect With a Mentor Commented:
Please show us your current GridView markup.

Where is the lblUserName located. Inside the GridView?

It's better to have a markup like..
<asp:TemplateField HeaderText="Chk">
                    <ItemTemplate>
                        <asp:Label ID="lbl1" runat="server"></asp:Label>
                    </ItemTemplate>
                    <EditItemTemplate>
                        <asp:TextBox ID="txt1" runat="server"></asp:TextBox>
                    </EditItemTemplate>
                </asp:TemplateField>


protected void gv1_RowDataBound(object sender, GridViewRowEventArgs e)
        {
            if (e.Row.RowType == DataControlRowType.DataRow)
            {
                TextBox txtbox = e.Row.FindControl("txt1") as TextBox;
                if (txtbox != null)
                {
                    txtbox.Text = lblUserName.Text;
                }
            }
        }

Open in new window

0
 
Alan WarrenConnect With a Mentor Applications DeveloperCommented:
Hi megnin,
Try something like this:
<%@ Page Language="VB" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<script runat="server">
  Protected Sub gv_RowCommand(sender As Object, e As System.Web.UI.WebControls.GridViewCommandEventArgs) Handles gv.RowCommand
      
    If e.CommandName = "Process" Then
      ' property to an Integer.
      Dim index As Integer = Convert.ToInt32(e.CommandArgument)

      ' Retrieve the row that contains the button clicked 
      ' by the user from the Rows collection.
      Dim row As GridViewRow = gv.Rows(index)

      ' update the value in column 2 with the value from column 1
      row.Cells(1).Text = row.Cells(0).Text
 
    End If
  End Sub
</script>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
</head>

<body>
    <form id="form1" runat="server">
    <div>
      <asp:gridview ID="gv" runat="server" AutoGenerateColumns="False" 
        DataSourceID="SomeSqlDataSource">
        <Columns>
          <asp:BoundField DataField="UserName" HeaderText="UserName" ReadOnly="True" 
            SortExpression="UserName" />
          <asp:BoundField DataField="ProcessedBy" HeaderText="ProcessedBy" 
            ReadOnly="True" SortExpression="ProcessedBy" />

          <asp:ButtonField ButtonType="Button" CommandName="Process" Text="Process" />
        </Columns>
        
       </asp:gridview>  
      
      
                  <asp:SqlDataSource 
                  ID="SomeSqlDataSource" runat="server" 
                  ConnectionString="<%$ ConnectionStrings:cnYourConnection %>" 
                  SelectCommand="select 'Me' as UserName, '' as ProcessedBy union all select 'You' as UserName, '' as ProcessedBy union all select 'Him' as UserName, '' as ProcessedBy"
                  >
              </asp:SqlDataSource>
  
    </div>
    </form>
</body>
</html> 

Open in new window

GridView - Populate field with value from another field in the same rowAlan ";0)
0
Free Tool: IP Lookup

Get more info about an IP address or domain name, such as organization, abuse contacts and geolocation.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

 
megninAuthor Commented:
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

0
 
megninAuthor Commented:
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.
0
 
Alan WarrenApplications DeveloperCommented:
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)
0
 
megninAuthor Commented:
Can't access "index" because it is "Friend".  Squiggly under "index".
0
 
Alan WarrenApplications DeveloperCommented:
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)
0
 
megninAuthor Commented:
Ha, yeah. ;)

Error      1      'CommandArgument' is not a member of 'System.Web.UI.WebControls.GridViewRowEventArgs'.
0
 
megninAuthor Commented:
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

0
 
CodeCruiserCommented:
Did you try http:#a38319415 ?
0
 
Alan WarrenApplications DeveloperCommented:
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)
0
 
megninAuthor Commented:
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.
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.