[Okta Webinar] Learn how to a build a cloud-first strategyRegister Now

x
?
Solved

Set the value of a TextBox in a Gridview

Posted on 2012-08-21
13
Medium Priority
?
3,766 Views
Last Modified: 2012-08-27
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".
0
Comment
Question by:megnin
  • 6
  • 4
  • 2
  • +1
13 Comments
 
LVL 20

Assisted Solution

by:informaniac
informaniac earned 668 total points
ID: 38319121
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
 
LVL 83

Accepted Solution

by:
CodeCruiser earned 668 total points
ID: 38319415
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
 
LVL 26

Assisted Solution

by:Alan Warren
Alan Warren earned 664 total points
ID: 38319533
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
VIDEO: THE CONCERTO CLOUD FOR HEALTHCARE

Modern healthcare requires a modern cloud. View this brief video to understand how the Concerto Cloud for Healthcare can help your organization.

 
LVL 1

Author Comment

by:megnin
ID: 38322293
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
 
LVL 1

Author Comment

by:megnin
ID: 38322383
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
 
LVL 26

Expert Comment

by:Alan Warren
ID: 38322921
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
 
LVL 1

Author Comment

by:megnin
ID: 38322935
Can't access "index" because it is "Friend".  Squiggly under "index".
0
 
LVL 26

Expert Comment

by:Alan Warren
ID: 38323090
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
 
LVL 1

Author Comment

by:megnin
ID: 38324834
Ha, yeah. ;)

Error      1      'CommandArgument' is not a member of 'System.Web.UI.WebControls.GridViewRowEventArgs'.
0
 
LVL 1

Author Comment

by:megnin
ID: 38325997
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
 
LVL 83

Expert Comment

by:CodeCruiser
ID: 38328431
Did you try http:#a38319415 ?
0
 
LVL 26

Expert Comment

by:Alan Warren
ID: 38328633
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
 
LVL 1

Author Closing Comment

by:megnin
ID: 38337601
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

Featured Post

Vote for the Most Valuable Expert

It’s time to recognize experts that go above and beyond with helpful solutions and engagement on site. Choose from the top experts in the Hall of Fame or on the right rail of your favorite topic page. Look for the blue “Nominate” button on their profile to vote.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

It was really hard time for me to get the understanding of Delegates in C#. I went through many websites and articles but I found them very clumsy. After going through those sites, I noted down the points in a easy way so here I am sharing that unde…
A while back, I ran into a situation where I was trying to use the calculated columns feature in SharePoint 2013 to do some simple math using values in two lists. Between certain data types not being accessible, and also with trying to make a one to…
The viewer will learn the basics of jQuery, including how to invoke it on a web page. Reference your jQuery libraries: (CODE) Include your new external js/jQuery file: (CODE) Write your first lines of code to setup your site for jQuery.: (CODE)
The viewer will learn the basics of jQuery including how to code hide show and toggles. Reference your jQuery libraries: (CODE) Include your new external js/jQuery file: (CODE) Write your first lines of code to setup your site for jQuery…
Suggested Courses
Course of the Month19 days, 1 hour left to enroll

834 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question