Learn how to a build a cloud-first strategyRegister Now

x
  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 813
  • Last Modified:

How to populate a TextBox in a GridView with the value of a Label when a CheckBox is checked.

In ASP.Net / VB I want to put the value of a Label into a TextBox in the row where a CheckBox is checked.

I have a basic Gridview with a TemplateField colum with a CheckBox called "Processed".  The next column is a regular BoundField called "Processed By".

I've put the logged in user's username into Label "lblUserName".

When a staff member checks the "Processed" CheckBox on a row I need their UserName from the lable to go into the "Processed By" field.  This is so we can see who processed what records.

The user may edit other fields in the row then click "Update" in the CommandField to save the data to the database.

Thanks.
0
megnin
Asked:
megnin
  • 39
  • 18
  • 3
  • +1
1 Solution
 
informaniacCommented:
gv is your gridview

protected void gv_RowDataBound(object sender, GridViewRowEventArgs e)
        {
            if (e.Row.RowType == DataControlRowType.DataRow<wbr ></wbr>)
            {
                CheckBox chkbox = e.Row.FindControl("chkbox"<wbr ></wbr>) as CheckBox;
                if (chkbox != null)
                {
                    chkbox.Attributes.Add("onc<wbr ></wbr>lick", "javascript:SetValue(this.id)<wbr ></wbr>;");
                }
            }
        }

Open in new window


Add this javascript code

function SetValue(chkboxid) {
            var chkboxObj = document.getElementById(chkboxid);
            var gv = document.getElementById("<% = gv.ClientID %>");
            var row;
            for (var i = 2; i < gv.rows.length; i++) {
                if (i < 10) {
                    row = "0" + i;
                }
                else
                    row = i;
                if (chkboxid == "gv_" + row + "_chk1") {
                    if (chkboxObj.checked) {
                        gv.rows[row].cells[1].innerHTML = document.getElementById("<% =lbl.ClientID %>").value;
                    }
                }
            }
            
        }

Open in new window

0
 
megninAuthor Commented:
Hi, thank you.

I don't understand these tags:  onc<wbr ></wbr>lick
They appear right in the middle of the word "onclick".  I would almost guess that all of the "<wbr></wbr>" tags don't belong there.  Maybe a copy/paste artifact?
0
 
megninAuthor Commented:
On:
            If chkbox <> Nothing Then

I'm getting:
Operator '<>' is not defined for type 'System.Web.UI.WebControls.CheckBox' and "System.Web.UI.WebControls.CheckBox.
0
Independent Software Vendors: We Want Your Opinion

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

 
megninAuthor Commented:
I fear in my efforts to make this work that I'm modifying your code to the point that it could never work.  ;-)  Let me post what I have now, including my actual control names.  Where have I screwed it up?
I did note that I'm using VB.
    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

Open in new window

<script type="text/javascript">
    function SetValue(chkboxid) {
        var chkboxObj = document.getElementById(chkboxid);
        
        var gv = document.getElementById("gv");
        var row;
        for (var i = 2; i < gv.rows.length; i++) {
            if (i < 10) {
                row = "0" + i;
            }
            else
                row = i;
            if (chkboxid == "gv_" + row + "_chk1") {
                if (chkboxObj.checked) {
                    
                    gv.rows[row].cells[1].innerHTML = document.getElementById("lblUserName").value;
                }
            }
        }

    }
</script>

Open in new window


And here's my checkbox:
                <asp:TemplateField HeaderText="Processed" SortExpression="Processed" ItemStyle-HorizontalAlign="Center">
                    <EditItemTemplate>
                        <asp:CheckBox ID="cbProcessed" runat="server" AutoPostBack="False"  Checked='<%# Bind("Processed") %>' />
                    </EditItemTemplate>
                    <ItemTemplate>
                        <asp:Label ID="lblProcessed" runat="server" Text='<%# Eval("Processed") %>'></asp:Label>
                    </ItemTemplate>
                </asp:TemplateField>
  

Open in new window

0
 
megninAuthor Commented:
In your javascript, what is "_chk1"?  I can find no place were that is defined.
0
 
informaniacCommented:
chk1 is the checkbox id in your case it is cbProcessed.
0
 
CodeCruiserCommented:
0
 
Alan WarrenCommented:
Had to set the checkbox.autopostback="true" to get a templatefield checkbox to fire an event; after which the gridview.rowcommand event is invoked, passing in the gridview.row.DataItemIndex as the commandargument.

The rest was fairly straightforward.

<%@ 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
      
    
    ' 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(1).Text = Me.Label1.Text
    
    ' 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
</script>

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

<body>
    <form id="form1" runat="server">
    <div>
      <asp:Label ID="Label1" runat="server" Text="Some User"></asp:Label>
      
      <asp:gridview ID="gv" runat="server" AutoGenerateColumns="False" 
        DataSourceID="SomeSqlDataSource" >
        <Columns>
          <asp:TemplateField>
            <ItemTemplate>
              <asp:CheckBox ID="Processed" runat="server" Checked="false" AutoPostBack="true" OnCheckedChanged="Processed_CheckedChanged" ></asp:CheckBox>
            </ItemTemplate>
          </asp:TemplateField>
          <asp:BoundField DataField="ProcessedBy" HeaderText="ProcessedBy" 
            ReadOnly="True" SortExpression="ProcessedBy" />

          <asp:BoundField DataField="UserName" HeaderText="UserName" ReadOnly="True" 
            SortExpression="UserName" />
        </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

Alan
0
 
megninAuthor Commented:
Alan,

On row 13 I changed row.Cells(1) to row.Cells(13).  (1) is the CustomerID column and the TextBox is in column (13).  I'm going to try changing that column back from a TemplateField to a BoundField because although the UserName did go into the column it replaced the TextBox with what looked like a label and it did not go into the database.
I think that was the only issue.  Using "Anything" or "Update" both worked the same in my usage.  I check the CheckBox... [user name] goes into column (13)... I click "Save/Update" in the Command Column and the CheckBox checked state goes into the database, but not the User Name.  I'll see if it works as a BoundField... Getting close...;-)
    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

        ' 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("Update", sender.namingcontainer.DataItemIndex)
        Dim GridViewCommandEventArgs As New GridViewCommandEventArgs(sender, CommandEventArgs)
        gv_RowCommand(gv, GridViewCommandEventArgs)
    End Sub

Open in new window

0
 
megninAuthor Commented:
... I forgot to post my current GridView markup.  These are columns (12) and (13):

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


Changing the Processed By field back to a BoundField made no difference.  I'll try looking at the Page Source and see if it's changing from a TextBox to a Label when the UserName gets written to it.
No, in the page source it's changing from an <input> before checking the box to just <td>username</td> after checking the box.
0
 
megninAuthor Commented:
Here:

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

Instead of referencing the cell, how would I reference the TextBox in the cell?  The TextBox ID, with the column as a TemplateField, is "txtProcessedBy".

I'm going to try this:

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

Well, that didn't work.  Object reference not set to an instance of an object on the tb.Text = line.
0
 
informaniacCommented:
Dim row As GridViewRow = sender.Rows(index)

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

Open in new window

0
 
megninAuthor Commented:
informaniac, I'm getting Object reference not set to an instance of an object on the tb.Text = line.  I think that's because the GV is in Edit Mode.
0
 
megninAuthor Commented:
I've added and then commented out so many bits of code now that I don't think anyone can make it work.
0
 
megninAuthor Commented:
This puts the User Name from the label into the TextBox in Edit mode, but when I click Save, the db is not updated.  Whether I check the checkbox or not doesn't matter.  The record is not updated in the db.
    ''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


If I comment out that entire Sub, and type something into the TextBox it is updated in the db.
0
 
Alan WarrenCommented:
Hi megnin,

in your last posted code block, invoke the update after populating the txt.text:
txt.Text = Me.lblUsername.Text
 gv.UpdateRow(sender.Rows(index), True)

Open in new window

Think you could also have invoked the update by populating the CommandName ("Anything") part of the CheckBox_Changed event, should be the same command name as defined in your SaveButton.
Dim CommandEventArgs As New CommandEventArgs("Update", sender.namingcontainer.DataItemIndex)

Open in new window

Alan
0
 
megninAuthor Commented:
I do have the "Update" line in place...

gv.UpdateRow gives me blue squigglies and:
Argument not specified for parameter 'rowIndex' of Public Overridable Sub UpdateRow(rowIndex As Integer, causesValidation As Boolean)'.

    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("Update", 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 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
            gv.UpdateRow()
        End If
    End Sub

Open in new window

0
 
Alan WarrenCommented:
Hi megnin,
Could possibly completely remove the event from the checkbox and do it all on gv.Rowcommand:
 Protected Sub gv_RowCommand(sender As Object, e As System.Web.UI.WebControls.GridViewCommandEventArgs) Handles gv.RowCommand
      
    If (row.RowType = DataControlRowType.DataRow) AndAlso ((row.RowState And DataControlRowState.Edit) > 0) Then
      Dim objCheckBox As CheckBox = Nothing
      Dim objTextBox As TextBox = Nothing
      
      objCheckBox = TryCast(row.FindControl("cbProcessed"), CheckBox)
      
      If objCheckBox IsNot Nothing Then
        With objCheckBox
          If .Checked = True Then
            objTextBox = TryCast(row.FindControl("txtProcessedBy"), TextBox)
            If objTextBox IsNot Nothing Then
              With objTextBox
                .Text = Me.lblUsername.Text
                .Dispose()
              End With
            End If
          End If
          .Dispose()
        End With
      End If
    End If
    
    gv.UpdateRow(sender.Rows(index), True)
    
  End Sub

Open in new window

Alan ";0)
0
 
megninAuthor Commented:
Can't access "row" or "index" because it is "Friend".  Blue squigglies under both.

I tried it with gv_RowDataBound removed and not removed.  Same result.
0
 
Alan WarrenCommented:
Hang on will try to make my version here editable.
0
 
Alan WarrenCommented:
Hi megnin,
the following code updates successfully without using the CheckBox_Changed event or explicitly invoking UpdateRow()

<%@ 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
    
    Dim objCheckBox As CheckBox = Nothing
    Dim objTextBox As TextBox = Nothing

    ' 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
     
      objCheckBox = TryCast(row.FindControl("cbProcessed"), CheckBox)
      
      If objCheckBox IsNot Nothing Then
        With objCheckBox
          If .Checked = True Then
            objTextBox = TryCast(row.FindControl("txtProcessedBy"), TextBox)
            If objTextBox IsNot Nothing Then
              With objTextBox
                .Text = Me.lblUsername.Text
                .Dispose()
              End With
            End If
          End If
          .Dispose()
        End With
      End If
    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:Label ID="lblUsername" runat="server" Text="Some User"></asp:Label>
       
      <asp:GridView ID="gv" runat="server" AutoGenerateColumns="False" 
        DataKeyNames="ID" DataSourceID="SomeSqlDataSource">
        <Columns>
          <asp:CommandField ShowEditButton="True" />
          <asp:BoundField DataField="ID" HeaderText="ID" InsertVisible="False" 
            ReadOnly="True" SortExpression="ID" />
          <asp:TemplateField>
            <EditItemTemplate>
              <asp:TextBox ID="UserNameTextBox" runat="server" Text='<%# Bind("UserName") %>' />
              <asp:TextBox ID="txtProcessedBy" runat="server" Text='<%# Bind("ProcessedBy") %>' />
              <asp:CheckBox ID="cbProcessed" runat="server" Checked='<%# Bind("Processed") %>' />
            </EditItemTemplate>
            <ItemTemplate>
              <asp:Label ID="UserNameLabel" runat="server" Text='<%# Eval("UserName") %>' />
              <asp:Label ID="lblProcessedBy" runat="server" Text='<%# Eval("ProcessedBy") %>' />
              <asp:CheckBox ID="ProcessedCheckBox" runat="server" Checked='<%# Eval("Processed") %>' Enabled="false" />
            </ItemTemplate>          
          </asp:TemplateField>
        </Columns>
      </asp:GridView>
        <asp:SqlDataSource 
            ID="SomeSqlDataSource" runat="server" 
            ConnectionString="<%$ ConnectionStrings:cnYourConnection %>" 
            SelectCommand="SELECT [ID], [UserName], [ProcessedBy], [Processed] FROM [Table_1]"
            UpdateCommand="Table_1_Upd" UpdateCommandType="StoredProcedure"
            >
          <UpdateParameters>
            <asp:Parameter Name="ID" Type="Int32" />
            <asp:Parameter Name="UserName" Type="String" />
            <asp:Parameter Name="ProcessedBy" Type="String" />
            <asp:Parameter Name="Processed" Type="Boolean" />
          </UpdateParameters>
        </asp:SqlDataSource>
  
    </div>
    </form>
</body>
</html>

Open in new window

Alan
0
 
Alan WarrenCommented:
Hi megnin,

If you are using a SqlDataSource to handle the update, you could skip all the other events and populate the UpdateParameter directly, using the current logged in users name.

  Protected Sub SomeSqlDataSource_Updating(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.SqlDataSourceCommandEventArgs) Handles SomeSqlDataSource.Updating

    e.Command.Parameters("ProcessedBy").Value = My.User.Name
    
  End Sub

Open in new window

Alan ";0)
0
 
megninAuthor Commented:
Ahhhhhh, I didn't think of that.  As long as the User Name goes into the correct record I don't need to see it in the Gridview.

I'll try both solutions and see which is easiest for me.
0
 
megninAuthor Commented:
Umm, I think I'll try the short one.  Regarding the long one, I have no UserName field in the database at all and no UserName column in the GV.  I'm just pulling the logged in user name from an environment variable and putting it in the lblUserName.  I was trying to then pull it from the label and put it in the "ProcessedBy" field when the "Processed" checkbox was checked.
0
 
megninAuthor Commented:
G%! @#$N!
    Protected Sub SqlDataSource1_Updating(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.SqlDataSourceCommandEventArgs) Handles SqlDataSource1.Updating

        e.Command.Parameters("ProcessedBy").Value = My.User.Name

    End Sub

Open in new window

<UpdateParameters>
    <asp:Parameter Name="StartDate" Type="DateTime" />
    <asp:Parameter Name="Processed" Type="String" />
    <asp:Parameter Name="ProcessedBy" Type="String" />
</UpdateParameters>

Open in new window


And I still get:

An SqlParameter with ParameterName 'ProcessedBy' is not contained by this SqlParameterCollection.
Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.

Exception Details: System.IndexOutOfRangeException: An SqlParameter with ParameterName 'ProcessedBy' is not contained by this SqlParameterCollection.

Source Error:


Line 20:     Protected Sub SqlDataSource1_Updating(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.SqlDataSourceCommandEventArgs) Handles SqlDataSource1.Updating
Line 21:
Line 22:         e.Command.Parameters("ProcessedBy").Value = My.User.Name
Line 23:
Line 24:     End Sub
 

Source File: E:\inetpub\www2\WP\Admin.aspx.vb    Line: 22

Jesus, I'm just going to tell the customer they have to type their name in the box.  ;-)
0
 
megninAuthor Commented:
This puts the right value into the TextBox when user clicks "Edit", but when user clicks "Save" it does not Update the database.  If I comment out that sub and type a value into the TextBox it does Update the database just fine.

    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 = e.Row ' 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

0
 
Alan WarrenCommented:
that's ok, more interested in your SqlDataSource1 now, the update parameters look ok, though I expect you probably have more.

can we have a look at the stored procedure that handles the update please?
Does the stored procedure expect and input parameter like:
  @ProcessedBy varchar(50) = NULL

if not then add one to the input parameters section of the sproc, I think the size for aspnet_users table, field username is 212, should probably check that and dimension the input param to handle the maximum size.

then in you your update SQL in the main section of the sproc, where you are setting the values: add another line [YourTableFieldName]=@ProcessedBy

That's it.

Alan
0
 
megninAuthor Commented:
I think I understand what I need to happen better now that when I first started the question, so let me re-state the question like this:

In the GridView, "gv", set the <EditItemTemplate> TextBox, "txtProcessedBy" Value to the value of a Label, "lblUserName", that's external to the GridView, when a user clicks "Edit" on a row.

That's it.  The CheckBox is irrelevant.
0
 
megninAuthor Commented:
Oh, Alan.  I just saw your last comment.  Hmmm, I don't have a stored procedure at all.  Simple ASP.Net GridView with nothing created programatically.  The code behind does absolutely nothing but put the logged in user name into lblUserName.Text.  All data is handled by the GridView/SqlDataSource1
0
 
megninAuthor Commented:
If I could just put the Text from that label into the TextBox, txtProcessedBy, somewhere other than the gv_RowDataBound event because that seems to be preventing any data from being written to the database.
0
 
Alan WarrenCommented:
Hi megnin,

stick with the one-liner in the SqlDataSource_Updating event.
The feedback is good!
Exception Details: System.IndexOutOfRangeException: An SqlParameter with ParameterName 'ProcessedBy' is not contained by this SqlParameterCollection.

Just add it to your input params in the storedprocedure, then make sure the actual field you want to store the username value in, consumes the input param.

Alan
0
 
megninAuthor Commented:
Or, send the value directly to the Update Parameter.  I had tried to do that but the line produced an error that was never addressed.
0
 
Alan WarrenCommented:
Can I take a peek at all of SqlDataSource1 please?
0
 
megninAuthor Commented:
I have no stored procedure.

This procuces an error so I removed it.

    Protected Sub SqlDataSource1_Updating(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.SqlDataSourceCommandEventArgs) Handles SqlDataSource1.Updating

        'e.Command.Parameters("ProcessedBy").Value = My.User.Name

    End Sub
0
 
megninAuthor Commented:
        <asp:SqlDataSource ID="SqlDataSource1" runat="server" ConflictDetection="CompareAllValues"
            ConnectionString="<%$ ConnectionStrings:WPConnectionString %>" DeleteCommand="DELETE FROM [ReturnToWork] WHERE [CustomerID] = @original_CustomerID AND (([LastName] = @original_LastName) OR ([LastName] IS NULL AND @original_LastName IS NULL)) AND (([FirstName] = @original_FirstName) OR ([FirstName] IS NULL AND @original_FirstName IS NULL)) AND (([Email] = @original_Email) OR ([Email] IS NULL AND @original_Email IS NULL)) AND (([CompanyName] = @original_CompanyName) OR ([CompanyName] IS NULL AND @original_CompanyName IS NULL)) AND [CompanyAddress] = @original_CompanyAddress AND [CompanyCity] = @original_CompanyCity AND [CompanyState] = @original_CompanyState AND [CompanyZip] = @original_CompanyZip AND [CompanyTelephone] = @original_CompanyTelephone AND (([StartDate] = @original_StartDate) OR ([StartDate] IS NULL AND @original_StartDate IS NULL))  AND (([Processed] = @original_Processed) OR ([Processed] IS NULL AND @original_Processed IS NULL)) AND (([ProcessedBy] = @original_ProcessedBy) OR ([ProcessedBy] IS NULL AND @original_ProcessedBy IS NULL))"
            InsertCommand="INSERT INTO [ReturnToWork] ([LastName], [FirstName], [Email], [CompanyName], [CompanyAddress], [CompanyCity], [CompanyState], [CompanyZip], [CompanyTelephone], [StartDate], [Processed], [ProcessedBy]) VALUES (@LastName, @FirstName, @Email, @CompanyName, @CompanyAddress, @CompanyCity, @CompanyState, @CompanyZip, @CompanyTelephone, @StartDate,  @Processed, @ProcessedBy)"
            OldValuesParameterFormatString="original_{0}" SelectCommand="SELECT [CustomerID], [LastName], [FirstName], [Email], [CompanyName], [CompanyAddress], [CompanyCity], [CompanyState], [CompanyZip], [CompanyTelephone], [StartDate], [Position], [Processed], [ProcessedBy] FROM [ReturnToWork] WHERE Processed = 0 ORDER BY [CustomerID]"
            UpdateCommand="UPDATE [ReturnToWork] SET [LastName] = @LastName, [FirstName] = @FirstName, [Email] = @Email, [CompanyName] = @CompanyName, [CompanyAddress] = @CompanyAddress, [CompanyCity] = @CompanyCity, [CompanyState] = @CompanyState, [CompanyZip] = @CompanyZip, [CompanyTelephone] = @CompanyTelephone, [StartDate] = @StartDate,  [Position] = @Position,  [Processed] = @Processed, [ProcessedBy] = @ProcessedBy WHERE [CustomerID] = @original_CustomerID AND (([LastName] = @original_LastName) OR ([LastName] IS NULL AND @original_LastName IS NULL)) AND (([FirstName] = @original_FirstName) OR ([FirstName] IS NULL AND @original_FirstName IS NULL)) AND (([Email] = @original_Email) OR ([Email] IS NULL AND @original_Email IS NULL)) AND (([CompanyName] = @original_CompanyName) OR ([CompanyName] IS NULL AND @original_CompanyName IS NULL)) AND [CompanyAddress] = @original_CompanyAddress AND [CompanyCity] = @original_CompanyCity AND [CompanyState] = @original_CompanyState AND [CompanyZip] = @original_CompanyZip AND [CompanyTelephone] = @original_CompanyTelephone AND (([StartDate] = @original_StartDate) OR ([StartDate] IS NULL AND @original_StartDate IS NULL))  AND (([Position] = @original_Position) OR ([Position] IS NULL AND @original_Position IS NULL))  AND (([Processed] = @original_Processed) OR ([Processed] IS NULL AND @original_Processed IS NULL)) AND (([ProcessedBy] = @original_ProcessedBy) OR ([ProcessedBy] IS NULL AND @original_ProcessedBy IS NULL))">
            <DeleteParameters>
                <asp:Parameter Name="original_CustomerID" Type="Int32" />
                <asp:Parameter Name="original_LastName" Type="String" />
                <asp:Parameter Name="original_FirstName" Type="String" />
                <asp:Parameter Name="original_Email" Type="String" />
                <asp:Parameter Name="original_CompanyName" Type="String" />
                <asp:Parameter Name="original_CompanyAddress" Type="String" />
                <asp:Parameter Name="original_CompanyCity" Type="String" />
                <asp:Parameter Name="original_CompanyState" Type="String" />
                <asp:Parameter Name="original_CompanyZip" Type="String" />
                <asp:Parameter Name="original_CompanyTelephone" Type="String" />
                <asp:Parameter Name="original_StartDate" Type="DateTime" />
                <asp:Parameter Name="original_Position" Type="String" />
                <asp:Parameter Name="original_Processed" Type="String" />
                <asp:Parameter Name="original_ProcessedBy" Type="String" />
            </DeleteParameters>
            <InsertParameters>
                <asp:Parameter Name="LastName" Type="String" />
                <asp:Parameter Name="FirstName" Type="String" />
                <asp:Parameter Name="Email" Type="String" />
                <asp:Parameter Name="CompanyName" Type="String" />
                <asp:Parameter Name="CompanyAddress" Type="String" />
                <asp:Parameter Name="CompanyCity" Type="String" />
                <asp:Parameter Name="CompanyState" Type="String" />
                <asp:Parameter Name="CompanyZip" Type="String" />
                <asp:Parameter Name="CompanyTelephone" Type="String" />
                <asp:Parameter Name="StartDate" Type="DateTime" />
                <asp:Parameter Name="Position" Type="String" />
                <asp:Parameter Name="Processed" Type="String" />
                <asp:Parameter Name="ProcessedBy" Type="String" />
            </InsertParameters>
            <UpdateParameters>
                <asp:Parameter Name="LastName" Type="String" />
                <asp:Parameter Name="FirstName" Type="String" />
                <asp:Parameter Name="Email" Type="String" />
                <asp:Parameter Name="CompanyName" Type="String" />
                <asp:Parameter Name="CompanyAddress" Type="String" />
                <asp:Parameter Name="CompanyCity" Type="String" />
                <asp:Parameter Name="CompanyState" Type="String" />
                <asp:Parameter Name="CompanyZip" Type="String" />
                <asp:Parameter Name="CompanyTelephone" Type="String" />
                <asp:Parameter Name="StartDate" Type="DateTime" />
                <asp:Parameter Name="Position" Type="String" />
                <asp:Parameter Name="Processed" Type="String" />
                <asp:Parameter Name="ProcessedBy" Type="String" />
                <asp:Parameter Name="original_CustomerID" Type="Int32" />
                <asp:Parameter Name="original_LastName" Type="String" />
                <asp:Parameter Name="original_FirstName" Type="String" />
                <asp:Parameter Name="original_Email" Type="String" />
                <asp:Parameter Name="original_CompanyName" Type="String" />
                <asp:Parameter Name="original_CompanyAddress" Type="String" />
                <asp:Parameter Name="original_CompanyCity" Type="String" />
                <asp:Parameter Name="original_CompanyState" Type="String" />
                <asp:Parameter Name="original_CompanyZip" Type="String" />
                <asp:Parameter Name="original_CompanyTelephone" Type="String" />
                <asp:Parameter Name="original_StartDate" Type="DateTime" />
                <asp:Parameter Name="original_Position" Type="String" />
                <asp:Parameter Name="original_Processed" Type="String" />
                <asp:Parameter Name="original_ProcessedBy" Type="String" />
            </UpdateParameters>
        </asp:SqlDataSource>

Open in new window

0
 
megninAuthor Commented:
Here is the GridView:
        <asp:GridView ID="gv" runat="server" DataSourceID="SqlDataSource1" 
            AutoGenerateColumns="False" DataKeyNames="CustomerID" CellPadding="4" 
            ForeColor="#333333">
            <AlternatingRowStyle BackColor="White" />
            <Columns>

 <%--
                <asp:BoundField DataField="ProcessedBy" HeaderText="Processed By" SortExpression="ProcessedBy">
                </asp:BoundField>
--%>
                
                <asp:CommandField ShowEditButton="True" UpdateText="Save" />
                <asp:BoundField DataField="CustomerID" HeaderText="CID" 
                    InsertVisible="False" ReadOnly="True" SortExpression="CustomerID" />
                <asp:BoundField DataField="LastName" HeaderText="Last Name" 
                    SortExpression="LastName" HeaderStyle-Wrap="False" ControlStyle-Width="100px">
<ControlStyle Width="100px"></ControlStyle>

<HeaderStyle Wrap="False"></HeaderStyle>
                </asp:BoundField>
                <asp:BoundField DataField="FirstName" HeaderText="First Name" 
                    SortExpression="FirstName" HeaderStyle-Wrap="False" ControlStyle-Width="100px">
<ControlStyle Width="100px"></ControlStyle>

<HeaderStyle Wrap="False"></HeaderStyle>
                </asp:BoundField>
                <asp:BoundField DataField="Email" HeaderText="Email" SortExpression="Email" 
                    ItemStyle-Wrap="False" ControlStyle-Width="180px">
<ControlStyle Width="180px"></ControlStyle>

<ItemStyle Wrap="False"></ItemStyle>
                </asp:BoundField>
                <asp:BoundField DataField="CompanyName" HeaderText="Company Name" 
                    SortExpression="CompanyName" HeaderStyle-Wrap="False" >
<HeaderStyle Wrap="False"></HeaderStyle>
                </asp:BoundField>
                <asp:BoundField DataField="CompanyAddress" HeaderText="Company Address" 
                    SortExpression="CompanyAddress" HeaderStyle-Wrap="False" ControlStyle-Width="200px">
<ControlStyle Width="200px"></ControlStyle>

<HeaderStyle Wrap="False"></HeaderStyle>
                </asp:BoundField>
                <asp:BoundField DataField="CompanyCity" HeaderText="Company City" 
                    SortExpression="CompanyCity" HeaderStyle-Wrap="False" 
                    ItemStyle-Wrap="False" >
<HeaderStyle Wrap="False"></HeaderStyle>

<ItemStyle Wrap="False"></ItemStyle>
                </asp:BoundField>
                <asp:BoundField DataField="CompanyState" HeaderText="State" 
                    SortExpression="CompanyState" ControlStyle-Width="25px" >
<ControlStyle Width="25px"></ControlStyle>
                </asp:BoundField>
                <asp:BoundField DataField="CompanyZip" HeaderText="Zip" 
                    SortExpression="CompanyZip" ControlStyle-Width="50px" >
<ControlStyle Width="50px"></ControlStyle>
                </asp:BoundField>
                <asp:BoundField DataField="CompanyTelephone" HeaderText="Comp. Telephone" 
                    SortExpression="CompanyTelephone" ItemStyle-Wrap="False" ControlStyle-Width="100px">
<ControlStyle Width="100px"></ControlStyle>

<ItemStyle Wrap="False"></ItemStyle>
                </asp:BoundField>
                <asp:BoundField DataField="StartDate" HeaderText="Start Date" 
                    SortExpression="StartDate" HtmlEncode="False" DataFormatString="{0:d}" 
                    ItemStyle-Wrap="False" ApplyFormatInEditMode="True" ControlStyle-Width="70px">
                    <ControlStyle Width="70px"></ControlStyle>
                    <ItemStyle Wrap="False"></ItemStyle>
                </asp:BoundField>
                <asp:BoundField DataField="Position" HeaderText="Position" 
                    SortExpression="Position" />
                <asp:TemplateField HeaderText="Processed" SortExpression="Processed" ItemStyle-HorizontalAlign="Center">
                    <EditItemTemplate>
                        <%--<asp:CheckBox ID="cbProcessed" runat="server" AutoPostBack="True" Checked='<%# Bind("Processed") %>' OnCheckedChanged="Processed_CheckedChanged" />--%>
                        <asp:CheckBox ID="cbProcessed" runat="server" AutoPostBack="False" Checked='<%# Bind("Processed") %>'  />
                    </EditItemTemplate>
                    <ItemTemplate>
                        <asp:Label ID="lblProcessed" runat="server" Text='<%# Eval("Processed") %>'></asp:Label>
                    </ItemTemplate>

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

                <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='<%# Eval("ProcessedBy") %>'></asp:Label>
                    </ItemTemplate>
                </asp:TemplateField>


            </Columns>
            <EditRowStyle BackColor="#7C6F57" />
            <FooterStyle BackColor="#1C5E55" Font-Bold="True" ForeColor="White" />
            <HeaderStyle BackColor="#1C5E55" Font-Bold="True" ForeColor="White" />
            <PagerStyle BackColor="#666666" ForeColor="White" HorizontalAlign="Center" />
            <RowStyle BackColor="#E3EAEB" />
            <SelectedRowStyle BackColor="#C5BBAF" Font-Bold="True" ForeColor="#333333" />
            <SortedAscendingCellStyle BackColor="#F8FAFA" />
            <SortedAscendingHeaderStyle BackColor="#246B61" />
            <SortedDescendingCellStyle BackColor="#D4DFE1" />
            <SortedDescendingHeaderStyle BackColor="#15524A" />
        </asp:GridView>

Open in new window

0
 
Alan WarrenCommented:
It was a good error megnin ";0)
0
 
megninAuthor Commented:
This is the error:

An SqlParameter with ParameterName 'ProcessedBy' is not contained by this SqlParameterCollection. 
Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code. 

Exception Details: System.IndexOutOfRangeException: An SqlParameter with ParameterName 'ProcessedBy' is not contained by this SqlParameterCollection.

Source Error: 


Line 20:     Protected Sub SqlDataSource1_Updating(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.SqlDataSourceCommandEventArgs) Handles SqlDataSource1.Updating
Line 21: 
Line 22:         e.Command.Parameters("ProcessedBy").Value = My.User.Name
Line 23: 
Line 24:     End Sub
 

Source File: E:\inetpub\www2\WP\Admin.aspx.vb    Line: 22 

Open in new window

0
 
megninAuthor Commented:
I'm afraid I don't understand.
0
 
Alan WarrenCommented:
Hi megnin,
Do you have access to the db, I mean can you open it using something like Sql Management Studio?

I've had a go at converting your inline SQL to a stored procedure, still need a little modification, mainly the paramater types and sizes, which you can get from the table definition by opening the table in design view, or scripting the table to a new query window.

USE [yourDatabaseCatalogName]
GO
/****** Object:  StoredProcedure [dbo].[megz_ReturnToWork_Upd]    Script Date: 08/24/2012 04:55:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE PROCEDURE [dbo].[megz_ReturnToWork_Upd] 
     -- These sizes and types need to be the same as defined 
     -- in the table design for table [ReturnToWork]
     @original_CustomerID INT = NULL
	,@original_LastName varchar(50) = NULL
	,@original_FirstName varchar(50) = NULL
	,@original_Email varchar(50) = NULL 
	,@original_CompanyName varchar(50) = NULL  
    ,@original_CompanyAddress varchar(50) = NULL
    ,@original_CompanyCity varchar(50) = NULL
    ,@original_CompanyState varchar(50) = NULL
    ,@original_CompanyZip varchar(50) = NULL
    ,@original_CompanyTelephone varchar(50) = NULL
    ,@original_StartDate datetime = NULL
    ,@original_Position varchar(50) = NULL
    ,@original_Processed varchar(50) = NULL
    ,@original_ProcessedBy varchar(50) = NULL

    ,@LastName varchar(50) = NULL
    ,@FirstName varchar(50) = NULL
    ,@Email varchar(50) = NULL
    ,@CompanyName varchar(50) = NULL
    ,@CompanyAddress varchar(50) = NULL
    ,@CompanyCity varchar(50) = NULL
    ,@CompanyState varchar(50) = NULL
    ,@CompanyZip varchar(50) = NULL
    ,@CompanyTelephone varchar(50) = NULL
	,@StartDate varchar(50) = NULL
	,@Position varchar(50) = NULL
	,@Processed varchar(50) = NULL
    ,@ProcessedBy varchar(256) = NULL -- The size of the username field in aspnet_users table
   
    
AS
BEGIN
    DECLARE @TranStarted   bit
    SET @TranStarted = 0

    IF( @@TRANCOUNT = 0 )
    BEGIN
    BEGIN TRANSACTION
    SET @TranStarted = 1
		
		UPDATE [ReturnToWork] 
		SET		 [LastName] = @LastName
				,[FirstName] = @FirstName
				,[Email] = @Email
				,[CompanyName] = @CompanyName
				,[CompanyAddress] = @CompanyAddress
				,[CompanyCity] = @CompanyCity
				,[CompanyState] = @CompanyState
				,[CompanyZip] = @CompanyZip
				,[CompanyTelephone] = @CompanyTelephone
				,[StartDate] = @StartDate
				,[Position] = @Position
				,[Processed] = @Processed
				,[ProcessedBy] = @ProcessedBy 
		
		WHERE [CustomerID] = @original_CustomerID 
		AND (([LastName] = @original_LastName) OR ([LastName] IS NULL AND @original_LastName IS NULL)) 
		AND (([FirstName] = @original_FirstName) OR ([FirstName] IS NULL AND @original_FirstName IS NULL)) AND (([Email] = @original_Email) OR ([Email] IS NULL AND @original_Email IS NULL)) 
		AND (([CompanyName] = @original_CompanyName) OR ([CompanyName] IS NULL AND @original_CompanyName IS NULL)) 
		AND [CompanyAddress] = @original_CompanyAddress 
		AND [CompanyCity] = @original_CompanyCity 
		AND [CompanyState] = @original_CompanyState 
		AND [CompanyZip] = @original_CompanyZip 
		AND [CompanyTelephone] = @original_CompanyTelephone 
		AND (([StartDate] = @original_StartDate) OR ([StartDate] IS NULL AND @original_StartDate IS NULL))  
		AND (([Position] = @original_Position) OR ([Position] IS NULL AND @original_Position IS NULL))  
		AND (([Processed] = @original_Processed) OR ([Processed] IS NULL AND @original_Processed IS NULL)) 
		AND (([ProcessedBy] = @original_ProcessedBy) OR ([ProcessedBy] IS NULL AND @original_ProcessedBy IS NULL))
    
    
    IF( @@ERROR <> 0 )
    BEGIN
        SET @TranStarted = 0
    	ROLLBACK TRANSACTION
    END

    IF( @TranStarted = 1 )
    BEGIN
	    SET @TranStarted = 0
	    COMMIT TRANSACTION
    END

    END
       
End

Open in new window



After modifying the parameter types and sizes, you need change your sqldatasource updatecommand="megz_ReturnToWork_Upd" and the updatecommandtype="StoredProcedure", check the types in the sqldatasource updateparameters section match your types in the sproc.
0
 
megninAuthor Commented:
I'm not sure we are both trying to do the same thing.
0
 
Alan WarrenCommented:
Hi megnin,


This parameter needs to be passed as one of the update parameters:
               <asp:Parameter Name="CustomerID" Type="Int32" />

These parameters are not being populated/bound anywhere by your gridview and will be passed as NULL in your update SQL:
                <asp:Parameter Name="original_CustomerID" Type="Int32" /> -- Cannot find '<%# Bind("original_CustomerID") %>'  in the gv template
                <asp:Parameter Name="original_LastName" Type="String" /> -- Cannot find '<%# Bind("original_LastName") %>'  in the gv template
                <asp:Parameter Name="original_FirstName" Type="String" /> -- same for the rest of these
                <asp:Parameter Name="original_Email" Type="String" />
                <asp:Parameter Name="original_CompanyName" Type="String" />
                <asp:Parameter Name="original_CompanyAddress" Type="String" />
                <asp:Parameter Name="original_CompanyCity" Type="String" />
                <asp:Parameter Name="original_CompanyState" Type="String" />
                <asp:Parameter Name="original_CompanyZip" Type="String" />
                <asp:Parameter Name="original_CompanyTelephone" Type="String" />
                <asp:Parameter Name="original_StartDate" Type="DateTime" />
                <asp:Parameter Name="original_Position" Type="String" />
                <asp:Parameter Name="original_Processed" Type="String" />
                <asp:Parameter Name="original_ProcessedBy" Type="String" />

So initially the update fails on:
WHERE [CustomerID] = @original_CustomerID  -- No match, @Original_CustomerID is null
AND (([LastName] = @original_LastName)  -- No match, @original_LastName is also Null, but I doubt that the field [LastName] is null, but it could be
OR ([LastName] IS NULL AND @original_LastName IS NULL)) -- This could be true

Alan ";0)
0
 
Alan WarrenCommented:
hi megnin,

look at your update logic, the following is a logical breakdown of the first WHERE caveat:
-- This:
		AND (([LastName] = @original_LastName) OR ([LastName] IS NULL AND @original_LastName IS NULL)) 
-- is the same as:
		AND (([LastName] = [LastName]) OR ([LastName] IS NULL AND @original_LastName IS NULL)) 
-- so this part can be taken out:
        ([LastName] = [LastName])
-- which leaves us with:
        [LastName] IS NULL AND @original_LastName IS NULL
-- which is the same as saying
   only do the update if the [lastname] field is null, but you can only update it with NULL  
   
-- The rest of your update WHERE caveats follow similar logic

Open in new window




Think you should change your WHERE condition to:
WHERE [CustomerID] = @CustomerID -- nothing else

Open in new window


Think you should also add CustomerID as an update parameter:
 <asp:Parameter Name="CustomerID" Type="Int32" />

Open in new window



Think you should remove from your update params:
               <asp:Parameter Name="original_CustomerID" Type="Int32" />
                <asp:Parameter Name="original_LastName" Type="String" />
                <asp:Parameter Name="original_FirstName" Type="String" />
                <asp:Parameter Name="original_Email" Type="String" />
                <asp:Parameter Name="original_CompanyName" Type="String" />
                <asp:Parameter Name="original_CompanyAddress" Type="String" />
                <asp:Parameter Name="original_CompanyCity" Type="String" />
                <asp:Parameter Name="original_CompanyState" Type="String" />
                <asp:Parameter Name="original_CompanyZip" Type="String" />
                <asp:Parameter Name="original_CompanyTelephone" Type="String" />
                <asp:Parameter Name="original_StartDate" Type="DateTime" />
                <asp:Parameter Name="original_Position" Type="String" />
                <asp:Parameter Name="original_Processed" Type="String" />
                <asp:Parameter Name="original_ProcessedBy" Type="String" />

Open in new window



Alan ";0)
0
 
megninAuthor Commented:
Hi Alan,

I agree I *can* remove the params with Name="original_****" because I've found out that there won't be the risk of contention because the customer says only one person will be working on this at any one time.

However, everything is working fine, except for getting the User Name into that text box.  That is all that is needed.  TextBox.Text = lblUserName.Text, Joy.  Every field is saved to the database just fine, Including that textbox value if I type something into it.  I just need something to put a username into it.
0
 
Alan WarrenCommented:
Hi David,
this should do the trick:
Invoke it from your edit template 'Update/Save' link/button.

Put a breakpoint on: If objTextBox IsNot Nothing Then
and step through it (F11) one line at a time.

 Protected Sub gv_RowCommand(sender As Object, e As System.Web.UI.WebControls.GridViewCommandEventArgs) Handles gv.RowCommand
    
 ' declare your variables
   Dim objTextBox As TextBox = Nothing

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

    ' Retrieve the row that contains the controls to be found
    Dim row As GridViewRow = sender.Rows(index)

    If (row.RowType = DataControlRowType.DataRow) AndAlso ((row.RowState And DataControlRowState.Edit) > 0) Then
      If row.RowState = DataControlRowState.Normal Or row.RowState = DataControlRowState.Alternate Then
        ' do stuff
            objTextBox = CType(row.FindControl("txtProcessedBy"), TextBox)
            If objTextBox IsNot Nothing Then
                With objTextBox
                    .Text =  Me.lblUsername.Text
                    .Dispose()
                End With
            End If

            ' ... do more stuff
        
      End If
    End If
    
  End Sub

Open in new window


If you were using a stored procedure we could use the one-liner:
  e.Command.Parameters("ProcessedBy").Value = My.User.Name
Thought we could even with inline parameterised SQL, but apparently not.


You may want to add an On_updated event to your either your gridview or your sqldatasource, one of them should expose .RowsAffected, a result of 1 would be nice.

Alan ";0)
0
 
Alan WarrenCommented:
Hi David,


If you are sure the update is working, this method of populating the txtProcessedBy textbox should do the job; it will populate when switching to edit mode.
Protected Sub txtProcessedBy_DataBinding(sender As Object, e As System.EventArgs)
    sender.text = My.User.Name
End Sub

Open in new window


Then in your gridview:
<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:
Hi Alan,

That does put the user name into the text box, but it does the same as the other routine that I said put the user name into the text box but does not Update the db.  When I click "Save/Update" in the GridView Command column the value of the textbox goes back to what it was before and no update goes to the database.
Other changed fields are not even updated so the entire update is failing.  Same as the other routine.  That routine is exactly 21 comments back from this one, for reference.  (btw, I'm not in the office today, so if I disapear for a little while it's to walk the dogs or something. ;-)
0
 
megninAuthor Commented:
I tried the gv_RowCommand
breakpoint on: If objTextBox IsNot Nothing Then - was never hit so txtProcessedBy was not set to user name.
If I typed something in the TextBox it was updated in the database, so updates still work with it in place.
0
 
Alan WarrenCommented:
Hi David,
Thought you had the Update sorted out:
http://www.experts-exchange.com/Programming/Languages/.NET/ASP.NET/Q_27836934.html#a38327621

However, everything is working fine, except for getting the User Name into that text box.  That is all that is needed.  TextBox.Text = lblUserName.Text, Joy.  Every field is saved to the database just fine, Including that textbox value if I type something into it.  I just need something to put a username into it.

Alan
0
 
megninAuthor Commented:
Is this correct:
If row.RowState = DataControlRowState.Normal   ?

Seems that ".Normal" would negate the line above.   e.g.  If 1 then if 0.   If 0 never happens.
0
 
megninAuthor Commented:
Well, the user name has to go into the text box AND the database Update obviously has to happen.  The two routines that put the User Name into the TextBox also DISABLED the Update making it moot.
0
 
Alan WarrenCommented:
Hi David,
you don't need any events except the one I posted here (txtProcessedBy_DataBinding):
http://www.experts-exchange.com/Programming/Languages/.NET/ASP.NET/Q_27836934.html#a38327742

And add to the txtProcessedBy textbox OnDataBinding="txtProcessedBy_DataBinding"

These do exactly same as the user typing something into the textbox.
The update will happen same as it does when you type something in.

Alan ";0)
0
 
megninAuthor Commented:
I commented out this If statement to see what would happen:

If row.RowState = DataControlRowState.Normal  

...and the user name did go into the database, only if no other changes were made to any other field in the GV.  If I checked the "Processed" CheckBox then the update failed.
If no other changes were made then my username went into the database.
0
 
megninAuthor Commented:
Just saw your comment 38328970.  Will try that now.
0
 
megninAuthor Commented:
I just tried it again and got the same result.  I had just tried it a few minutes ago when you first posted that.  Here was my result then.  Same as this time.  http://www.experts-exchange.com/Programming/Languages/.NET/ASP.NET/Q_27836934.html#a38328839

I agree that it should be the same as typing into the text box, but it disables any db update.  Fact.
0
 
megninAuthor Commented:
If I only comment out ' sender.text = My.User.Name, then I can type something in the text box and make any other change and it is saved to the db.

If I put it back and hard code a value, "sender.text = "test", then the update fails.  Nothing goes to the db.
0
 
Alan WarrenCommented:
No other script blocks firing other than txtProcessedBy_DataBinding?
Which we have confirmed, populates the textbox with the current logged in user name.

And the current logged in user name is the same as the previous user name @original_ProcessedBy?

or your last Where condition will negate the update:
AND (([ProcessedBy] = @original_ProcessedBy) OR ([ProcessedBy] IS NULL AND @original_ProcessedBy IS NULL))
   
   

I don't understand it either, the update should be the same it would be if you had typed it in manually.

 
Alan
0
 
megninAuthor Commented:
I'm going to change my datasource configuration to remove the concurrency checks, "@original_***" and see if that makes any difference.
0
 
megninAuthor Commented:
Well, that seems to have been the problem.
I removed the "optomistic concurrency" from the SqlDataSource configuration and now that sub works as it should.  When I click "Edit" on a field, the Username goes into the TextBox and into the DB.  :-)
0
 
megninAuthor Commented:
It seems that the optomistic concurrency check was seeing one databind and then preventing a subsequent databind from overwriting any change, thus making the update fail.  It kind of makes sense, but what a pain it makes it.
0
 
megninAuthor Commented:
Once I removed the "Optimistic Concurrency" this worked fine.  I'm pretty sure that the other methods you suggested would have also worked without the Optimistic Concurrency thing blocking DB updates where there the process required more than one "databind".

Thank you for sticking with me and all of your patience when your suggestions clearly should have worked.

I learned a lot about GridViews with this one!
0

Featured Post

Technology Partners: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

  • 39
  • 18
  • 3
  • +1
Tackle projects and never again get stuck behind a technical roadblock.
Join Now