Want to protect your cyber security and still get fast solutions? Ask a secure question today.Go Premium

x
?
Solved

Need to Log When Edit Occurs in Gridview

Posted on 2009-04-15
37
Medium Priority
?
764 Views
Last Modified: 2013-11-07
I've created an ASP gridview and made it editable. It displays the information that was entered into a SQL table plus a time stamp and the submitter's user ID.

In the event information is edited on a specific row, I need to overwrite the time stamp, and requestor on that row to show who edited the entry. The part I'm unsure about is how single out the row that the edit occured so that I'm only writing to the row that was edited.

I'd really like to able to work this from ASP and VB as opposed to SQL methods. Below is the code for my gridview, and a PNG of the SQL table.

Thanks.

Thanks
<div class="gridview-container">           	     
	        <asp:GridView ID="GridView1" DataSourceID="SqlDataSource1" runat="server" DataKeyNames="Sequence"
            wrap="false" ForeColor="Black" ShowFooter="True" CellPadding="5"                    
            BackColor="White" BorderWidth="1px" BorderStyle="None" BorderColor="#CCCCCC" 
                 Height="135px" AllowPaging="True" AllowSorting="True" 
                 AutoGenerateEditButton="True" AutoGenerateColumns="False">
                <Columns>
                    <asp:BoundField DataField="Sequence" HeaderText="Sequence" 
                        SortExpression="Sequence" InsertVisible="False" ReadOnly="True" />
                    <asp:BoundField DataField="DeptID" HeaderText="Dept ID" 
                        SortExpression="DeptID" />
                    <asp:BoundField DataField="Dept" HeaderText="Dept" SortExpression="Dept" />
                    <asp:BoundField DataField="DeptOU" HeaderText="Dept OU" 
                        SortExpression="DeptOU" />
                    <asp:BoundField DataField="InstOU" HeaderText="Institution OU" 
                        SortExpression="InstOU" />
                    <asp:BoundField DataField="HomeDir" HeaderText="Home Directory" 
                        SortExpression="HomeDir" />
                    <asp:BoundField DataField="Groups" HeaderText="Groups" 
                        SortExpression="Groups" />
                    <asp:BoundField DataField="Contact" HeaderText="Contact" 
                        SortExpression="Contact" />
                    <asp:BoundField DataField="Phone" HeaderText="Phone" SortExpression="Phone" />
                    <asp:BoundField DataField="Email" HeaderText="Email" SortExpression="Email" />
                    <asp:BoundField DataField="ZoneMgr" HeaderText="Zone Manager" 
                        SortExpression="ZoneMgr" />
                    <asp:BoundField DataField="Submitted" HeaderText="Submitted" 
                        SortExpression="Submitted" />
                    <asp:BoundField DataField="Requestor" HeaderText="Requestor" 
                        SortExpression="Requestor" />
                </Columns>
            <HeaderStyle Font-Bold="true" Wrap="false" ForeColor="White" BackColor="#333333" /> 
            <FooterStyle Font-Bold="true" Wrap="false" ForeColor="White" BackColor="#333333" />                
            <AlternatingRowStyle Font-Bold="True" Wrap="False" ForeColor="black" BackColor="#CCCC99"></AlternatingRowStyle>
           </asp:GridView>
                
	     <asp:SqlDataSource ID="SqlDataSource1" runat="server"
	            SelectCommand="SELECT * FROM [Automated_ZM_Dept_Request]"
                ConnectionString="<%$ ConnectionStrings:MyConnection2 %>"                  
                DataSourceMode="DataSet"
                UpdateCommand="UPDATE [Automated_ZM_Dept_Request] SET [DeptID] = @DeptID, [Dept] = @Dept, [DeptOU] = @DeptOU, [InstOU] = @InstOU, [HomeDir] = @HomeDir, [Groups] = @Groups, [Contact] = @Contact, [Phone] = @Phone, [Email] = @Email, [ZoneMgr] = @ZoneMgr, [Submitted] = @Submitted, [Requestor] = @Requestor WHERE [Sequence] = @Sequence">
                <UpdateParameters>
                    <asp:Parameter Type="String" Name="Sequence"></asp:Parameter>                
                    <asp:Parameter Type="String" Name="DeptID"></asp:Parameter>
                    <asp:Parameter Type="String" Name="Dept"></asp:Parameter>
                    <asp:Parameter Type="String" Name="DeptOU"></asp:Parameter>
                    <asp:Parameter Type="String" Name="InstOU"></asp:Parameter>
                    <asp:Parameter Type="String" Name="HomeDir"></asp:Parameter>
                    <asp:Parameter Type="String" Name="Groups"></asp:Parameter>
                    <asp:Parameter Type="String" Name="Contact"></asp:Parameter>
                    <asp:Parameter Type="String" Name="Phone"></asp:Parameter>
                    <asp:Parameter Type="String" Name="Email"></asp:Parameter>
                    <asp:Parameter Type="String" Name="ZoneMgr"></asp:Parameter>
                    <asp:Parameter Type="String" Name="Submitted"></asp:Parameter>
                    <asp:Parameter Type="String" Name="Requestor"></asp:Parameter>
                </UpdateParameters>
             </asp:SqlDataSource>                         
		 </div> <!-- end gridview-container -->

Open in new window

SQL-Table.png
0
Comment
Question by:JB4375
  • 19
  • 18
37 Comments
 
LVL 96

Expert Comment

by:Bob Learned
ID: 24157476
1) You need to handle the RowEditing event.

2) I noticed that you had wrap="false" in the GridView definition.  I believe that a better way is to set the RowStyle:Wrap="False" instead.

3) New HTML and code shown below:
    <asp:GridView ID="GridView1" DataSourceID="SqlDataSource1" runat="server" DataKeyNames="Sequence"
      ForeColor="Black" ShowFooter="True" CellPadding="5" BackColor="White"
      BorderWidth="1px" BorderStyle="None" BorderColor="#CCCCCC" Height="135px" AllowPaging="True"
      AllowSorting="True" AutoGenerateEditButton="True" AutoGenerateColumns="False">
      <Columns>
        <asp:BoundField DataField="Sequence" HeaderText="Sequence" SortExpression="Sequence"
          InsertVisible="False" ReadOnly="True" >
        </asp:BoundField>
        <asp:BoundField DataField="DeptID" HeaderText="Dept ID" SortExpression="DeptID" />
        <asp:BoundField DataField="Dept" HeaderText="Dept" SortExpression="Dept" />
        <asp:BoundField DataField="DeptOU" HeaderText="Dept OU" SortExpression="DeptOU" />
        <asp:BoundField DataField="InstOU" HeaderText="Institution OU" SortExpression="InstOU" />
        <asp:BoundField DataField="HomeDir" HeaderText="Home Directory" SortExpression="HomeDir" />
        <asp:BoundField DataField="Groups" HeaderText="Groups" SortExpression="Groups" />
        <asp:BoundField DataField="Contact" HeaderText="Contact" SortExpression="Contact" />
        <asp:BoundField DataField="Phone" HeaderText="Phone" SortExpression="Phone" />
        <asp:BoundField DataField="Email" HeaderText="Email" SortExpression="Email" />
        <asp:BoundField DataField="ZoneMgr" HeaderText="Zone Manager" SortExpression="ZoneMgr" />
        <asp:BoundField DataField="Submitted" HeaderText="Submitted" SortExpression="Submitted" />
        <asp:BoundField DataField="Requestor" HeaderText="Requestor" SortExpression="Requestor" />
      </Columns>
      <HeaderStyle Font-Bold="True" Wrap="False" ForeColor="White" BackColor="#333333" />
      <FooterStyle Font-Bold="True" Wrap="False" ForeColor="White" BackColor="#333333" />
      <AlternatingRowStyle Font-Bold="True" Wrap="False" ForeColor="Black" BackColor="#CCCC99" />
      <RowStyle Wrap="False" />
    </asp:GridView>
 
 
 
 
    Protected Sub GridView1_RowEditing(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewEditEventArgs) Handles GridView1.RowEditing
        Dim row As GridViewRow = Me.GridView1.Rows(e.NewEditIndex)
        Dim drv As DataRowView = TryCast(row.DataItem, DataRowView)
        Dim sequence As String = drv("Sequence").ToString()
    End Sub

Open in new window

0
 
LVL 1

Author Comment

by:JB4375
ID: 24157772
Ok... Just to confirm the changes:

*Removed Wrap=False
* Added <RowStyle Wrap="False" />
*Added the protected sub the VB side
*Added Imports System.Data

I tested the edit function and got the following error:
 Object reference not set to an instance of an object.  

Exception Details: System.NullReferenceException: Object reference not set to an instance of an object.
Stack Trace:

[NullReferenceException: Object reference not set to an instance of an object.] _Default.GridView1_RowEditing(Object sender, GridViewEditEventArgs e) +64 System.Web.UI.WebControls.GridView.OnRowEditing(GridViewEditEventArgs e) +133 System.Web.UI.WebControls.GridView.HandleEdit(Int32 rowIndex) +40 System.Web.UI.WebControls.GridView.HandleEvent(EventArgs e, Boolean causesValidation, String validationGroup) +673 System.Web.UI.WebControls.GridView.RaisePostBackEvent(String eventArgument) +199 System.Web.UI.WebControls.GridView.System.Web.UI.IPostBackEventHandler.RaisePostBackEvent(String eventArgument) +7 System.Web.UI.Page.RaisePostBackEvent(IPostBackEventHandler sourceControl, String eventArgument) +11 System.Web.UI.Page.RaisePostBackEvent(NameValueCollection postData) +177 System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint) +1746  
0
 
LVL 96

Expert Comment

by:Bob Learned
ID: 24164192
I would think that error is about this line:

Dim drv As DataRowView = TryCast(row.DataItem, DataRowView)

That usually happens because the GridView.DataSource is not set.
0
Industry Leaders: 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!

 
LVL 1

Author Comment

by:JB4375
ID: 24164487
The data source is set. As soon as I hit submit, it does another bind to show the last table entry in the grid. It also sorts on any column, takes edits etc.
OK... One thing I've noticed.... hovering over the edit link displays the following:
javascript:_doPostBack('Gridview1','Edit$0')
With other objects like a DropDownList, I can setup a SelectedIndexChanged event. However when I click anywhere on the gridview it generates the same event no matter where I clicks.
Thanks.
0
 
LVL 96

Expert Comment

by:Bob Learned
ID: 24169755
If the DataSource is set, then where are you getting the error?
0
 
LVL 1

Author Comment

by:JB4375
ID: 24170407
I'm sorry... but I'm not following you.....DataSourceID="SqlDataSource1". I'm able to add from the form, and update the fields etc.
Are suggesting that I need to have a SQL connection established on the Protected Sub GridView1_RowEditing?
0
 
LVL 96

Expert Comment

by:Bob Learned
ID: 24171566
No, you have set the DataSourceID (which is correct), but you haven't indicated what exact line that you are getting that exception (my last attempt was only a guess).
0
 
LVL 1

Author Comment

by:JB4375
ID: 24171701
Sorry about that....
The error occurs here: Dim sequence As String = drv("Sequence").ToString()
 
0
 
LVL 96

Expert Comment

by:Bob Learned
ID: 24172075
Next possibility--row.DataItem is not a DataRowView, so the TryCast returns nothing (not an exception).  

What is row.DataItem.GetType().Name?
0
 
LVL 1

Author Comment

by:JB4375
ID: 24172684
I could be way off base, and probably am, in what you wanted me to do. I commented out the original line, and added the edited line below. I'm get the following error on the new line: "value of type string cannot be converted to system.data.data.datarowview"

Protected Sub GridView1_RowEditing(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewEditEventArgs) Handles GridView1.RowEditing
        Dim row As GridViewRow = Me.GridView1.Rows(e.NewEditIndex)
        ' Dim drv As DataRowView = TryCast(row.DataItem, DataRowView)
        Dim drv As DataRowView = TryCast(row.DataItem.GetType.Name(), DataRowView)
        Dim sequence As String = drv("Sequence").ToString()
    End Sub

Open in new window

0
 
LVL 96

Expert Comment

by:Bob Learned
ID: 24172721
Nope, that would be:

Dim typeName As String = row.DataItem.GetType().Name
0
 
LVL 1

Author Comment

by:JB4375
ID: 24172914
I established breakpoints on:
 Dim typeName As String = row.DataItem.GetType().Name
 Dim drv As DataRowView = TryCast(row.DataItem, DataRowView)
I selected the edit row. At this point the value of typeName is nothing. When I step into the next statement is errors out again.

Protected Sub GridView1_RowEditing(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewEditEventArgs) Handles GridView1.RowEditing
        Dim row As GridViewRow = Me.GridView1.Rows(e.NewEditIndex)
        Dim typeName As String = row.DataItem.GetType().Name
        Dim drv As DataRowView = TryCast(row.DataItem, DataRowView)
        Dim sequence As String = drv("Sequence").ToString()
    End Sub

Open in new window

0
 
LVL 96

Expert Comment

by:Bob Learned
ID: 24174861
Hmmm...what value are you trying to get?  Maybe trying to use FindControl, to get the editing control would be a better approach here...I don't know why row.DataItem is Nothing...
0
 
LVL 1

Author Comment

by:JB4375
ID: 24175129
Well, the link on the edit column shows: javascript:_doPostBack('Gridview1','Edit$0') where $0 represents the first row, $1 the second and so on.
I was under the impression that as long as I was capturing that portion, when I updated I could specifiy that row and write the time stamp to submitted and the userID to requestor.
However, now that I'm looking at it for 100th time or so, it looks like it needs to run when the actual update occurs. The update link for the same row is:
javascript:__doPostBack('GridView1$ctl02$ctl00','')
 
0
 
LVL 96

Expert Comment

by:Bob Learned
ID: 24175327
I set up a small test, so that I could get something working.
Detect-GridView-RowEditing-Event.doc
0
 
LVL 1

Author Comment

by:JB4375
ID: 24187181
Sorry for the long delay. I usually remote to my work PC from home. We had a patch that went through and I was unable to remote in.
I've installed SQL Server Express Edition with full tools etc. and attached AdventureWorks db. I've gotten the Detect-GridView-RowEditing-Event program setup and it's connnecting fine. I'm able to view the output.
What's the next step?
JB
Thanks again for your patience, putting so much into this.
0
 
LVL 1

Author Comment

by:JB4375
ID: 24187204
Correction:
When I attempt to update, I get the following error:
System.NotSupportedException: Updating is not supported by data source 'EmployeeDataSource' unless UpdateCommand is specified.
Stack Trace:

[NotSupportedException: Updating is not supported by data source 'EmployeeDataSource' unless UpdateCommand is specified.] System.Web.UI.WebControls.SqlDataSourceView.ExecuteUpdate(IDictionary keys, IDictionary values, IDictionary oldValues) +1872903 System.Web.UI.DataSourceView.Update(IDictionary keys, IDictionary values, IDictionary oldValues, DataSourceViewOperationCallback callback) +78 System.Web.UI.WebControls.GridView.HandleUpdate(GridViewRow row, Int32 rowIndex, Boolean causesValidation) +1215 System.Web.UI.WebControls.GridView.HandleEvent(EventArgs e, Boolean causesValidation, String validationGroup) +837 System.Web.UI.WebControls.GridView.OnBubbleEvent(Object source, EventArgs e) +95 System.Web.UI.Control.RaiseBubbleEvent(Object source, EventArgs args) +35 System.Web.UI.WebControls.GridViewRow.OnBubbleEvent(Object source, EventArgs e) +117 System.Web.UI.Control.RaiseBubbleEvent(Object source, EventArgs args) +35 System.Web.UI.WebControls.LinkButton.OnCommand(CommandEventArgs e) +115 System.Web.UI.WebControls.LinkButton.RaisePostBackEvent(String eventArgument) +132 System.Web.UI.WebControls.LinkButton.System.Web.UI.IPostBackEventHandler.RaisePostBackEvent(String eventArgument) +7 System.Web.UI.Page.RaisePostBackEvent(IPostBackEventHandler sourceControl, String eventArgument) +11 System.Web.UI.Page.RaisePostBackEvent(NameValueCollection postData) +177 System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint) +1746
 
0
 
LVL 96

Expert Comment

by:Bob Learned
ID: 24187701
That just means that you don't have an UpdateCommand defined for the SqlDataSource.
0
 
LVL 1

Author Comment

by:JB4375
ID: 24188031
Right.... SQLDataSource config below. Error that I'm getting:
System.Data.SqlClient.SqlException: Invalid object name 'HumanResources.vEmployee'.
[SqlException (0x80131904): Invalid object name 'HumanResources.vEmployee'.] System.Data.SqlClient.SqlConnection.OnError(SqlException exception, Boolean breakConnection) +925466 System.Data.SqlClient.SqlInternalConnection.OnError(SqlException exception, Boolean breakConnection) +800118 System.Data.SqlClient.TdsParser.ThrowExceptionAndWarning(TdsParserStateObject stateObj) +186 System.Data.SqlClient.TdsParser.Run(RunBehavior runBehavior, SqlCommand cmdHandler, SqlDataReader dataStream, BulkCopySimpleResultSet bulkCopyHandler, TdsParserStateObject stateObj) +1932 System.Data.SqlClient.SqlCommand.FinishExecuteReader(SqlDataReader ds, RunBehavior runBehavior, String resetOptionsString) +149 System.Data.SqlClient.SqlCommand.RunExecuteReaderTds(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, Boolean async) +1005 System.Data.SqlClient.SqlCommand.RunExecuteReader(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, String method, DbAsyncResult result) +132 System.Data.SqlClient.SqlCommand.InternalExecuteNonQuery(DbAsyncResult result, String methodName, Boolean sendToPipe) +149 System.Data.SqlClient.SqlCommand.ExecuteNonQuery() +135 System.Web.UI.WebControls.SqlDataSourceView.ExecuteDbCommand(DbCommand command, DataSourceOperation operation) +404 System.Web.UI.WebControls.SqlDataSourceView.ExecuteUpdate(IDictionary keys, IDictionary values, IDictionary oldValues) +721 System.Web.UI.DataSourceView.Update(IDictionary keys, IDictionary values, IDictionary oldValues, DataSourceViewOperationCallback callback) +78 System.Web.UI.WebControls.GridView.HandleUpdate(GridViewRow row, Int32 rowIndex, Boolean causesValidation) +1215 System.Web.UI.WebControls.GridView.HandleEvent(EventArgs e, Boolean causesValidation, String validationGroup) +837 System.Web.UI.WebControls.GridView.OnBubbleEvent(Object source, EventArgs e) +95 System.Web.UI.Control.RaiseBubbleEvent(Object source, EventArgs args) +35 System.Web.UI.WebControls.GridViewRow.OnBubbleEvent(Object source, EventArgs e) +117 System.Web.UI.Control.RaiseBubbleEvent(Object source, EventArgs args) +35 System.Web.UI.WebControls.LinkButton.OnCommand(CommandEventArgs e) +115 System.Web.UI.WebControls.LinkButton.RaisePostBackEvent(String eventArgument) +132 System.Web.UI.WebControls.LinkButton.System.Web.UI.IPostBackEventHandler.RaisePostBackEvent(String eventArgument) +7 System.Web.UI.Page.RaisePostBackEvent(IPostBackEventHandler sourceControl, String eventArgument) +11 System.Web.UI.Page.RaisePostBackEvent(NameValueCollection postData) +177 System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint) +1746

 

    <asp:SqlDataSource ID="EmployeeDataSource" runat="server" SelectCommand="SELECT * FROM HumanResources.vEmployee"
        ConnectionString="<%$ ConnectionStrings:AdventureWorks %>" 
        DataSourceMode="DataSet"
        UpdateCommand="Update [HumanResources.vEmployee] SET [FirstName] = @FirstName, [LastName] = @LastName, [JobTitle] = @JobTitle, [Phone] = @Phone, [EmailAddress] = @EmailAddress, [AddressLine1] = @AddressLine1, [City] = @City, [StateProvinceName] = @StateProvinceName, [PostalCode] = @PostalCode, [CountryRegionName] = @CountryRegionName WHERE [EmployeeID] = @EmployeeID">
    </asp:SqlDataSource>

Open in new window

0
 
LVL 96

Expert Comment

by:Bob Learned
ID: 24189856
That example is probably not the "perfect" example for you.  I have SQL Server 2008, and I don't know what version of AdventureWorks you are working with.
0
 
LVL 1

Author Comment

by:JB4375
ID: 24190377
I'm using Visual Studio 2008, SQL 2005, and was careful to get the corresponding version of AdventureWorks.
0
 
LVL 96

Expert Comment

by:Bob Learned
ID: 24192953
Do you have SQL Server Management Studio?  If you do, then I would suggest opening the AdventureWorks database, and making sure that you have that view in the HumanResources schema.  

That example was meant for me to understand the issue, and to work out a possible solution.  If it is not working for you (since you are getting exceptions), then we can talk through how it can help you.

The important code is the RowEditing handler.  Instead of getting the DataItem, you can get the value from the cell text.  The e.NewEditIndex should indicate which GridViewRow you need to work with.


Protected Sub EmployeeGridView_RowEditing(ByVal sender As Object, _
                                              ByVal e As System.Web.UI.WebControls.GridViewEditEventArgs) _
                                              Handles EmployeeGridView.RowEditing
        ' Get the info about the edited row
        Dim employeeID As String = EmployeeGridView.Rows(e.NewEditIndex).Cells(1).Text
        Dim firstName As String = EmployeeGridView.Rows(e.NewEditIndex).Cells(2).Text
        Dim lastName As String = EmployeeGridView.Rows(e.NewEditIndex).Cells(3).Text
    End Sub

Open in new window

0
 
LVL 1

Author Comment

by:JB4375
ID: 24198135
I've been using SQL Management Server. I wasn't able to install AdventureWorks on a production box. Enter SQL Express.
My original program works with the upates. Any way we can just go with that?
0
 
LVL 96

Expert Comment

by:Bob Learned
ID: 24198698
Yes, you should be able to use your original program, and add code similar to the RowEditing event handler.
0
 
LVL 1

Author Comment

by:JB4375
ID: 24214474
I'm at a loss on this. However, I did manage to find the following on handling an update:
Create an UpdateCommand Handler
Copy the generic SetDatasetValuesFromGrid reverse binding code.
You should add a new ElseIf section for each type of control you will be using in the grid.
This instance handles TextBoxes and CheckBoxes.

'Generic Code to do Reverse binding from a DataGridItem cell to its 'corresponding DataTable item. Private Sub SetDatasetValuesFromGrid(ByVal DataTable As DataTable, _ ByVal DataTableColumnName As String, _ ByVal DataGridItem As DataGridItem, _ ByVal DataGridCellIndex As Integer) For Each control As Control In DataGridItem.Cells(DataGridCellIndex).Controls If TypeOf control Is CheckBox Then Me.DatasetEditGrid1.EditGrid(DataGridItem.DataSetIndex)(DataTableColumnName) _ = CType(control, CheckBox).Checked Exit For ElseIf TypeOf control Is TextBox Then Me.DatasetEditGrid1.EditGrid(DataGridItem.DataSetIndex)(DataTableColumnName) _ = CType(control, TextBox).Text Exit For End If Next End Sub 
Call the SetDatasetValuesFromGrid for each cell in the edit row.
Use an Enum to correlate the Dataset Column Names to the Grid's Column indexes.
Save the dataset to your datasource using an adapter.update. (Not done in this example)
Reset the EditItemIndex. Collapse Copy Code Private Sub DataGrid1_UpdateCommand(ByVal source As Object, _ ByVal e As System.Web.UI.WebControls.DataGridCommandEventArgs) _ Handles DataGrid1.UpdateCommand UpdateDatasetFromGrid() Me.DataGrid1.EditItemIndex = -1 End Sub 'Relate the Dataset's Column Names to the Column Index in the Datagrid Private Enum DatasetColumnNameToGridColumnIndex Name = 1 Location = 2 ClockedIn = 3 End Enum 'Reverse bind from the datagrid to the dataset. Private Sub UpdateDatasetFromGrid() For Each ColName As DatasetColumnNameToGridColumnIndex _ In System.Enum.GetValues(GetType(DatasetColumnNameToGridColumnIndex)) SetDatasetValuesFromGrid(Me.DatasetEditGrid1.EditGrid, ColName.ToString, _ Me.DataGrid1.Items(Me.DataGrid1.EditItemIndex), ColName) Next 'Normally you would save (adapter.update) to the database here. End Sub 

Open in new window

0
 
LVL 96

Expert Comment

by:Bob Learned
ID: 24217739
Did that solve your problem?
0
 
LVL 1

Author Comment

by:JB4375
ID: 24217865
I'm still playing with it. I've gotten pulled into a couple "more immediate" problems, PLUS migrating about 10 tables to a new server, and updating the associated connection strings, PLUS figuring out how import a CSV file into SQL.
I hate to have you keep coming back to this... we've been going back and forth for nearly a week. What's the protocol in this type of situation? I'm tempted to award points, and close the question. I had no idea this "one last change" was going to take more time than the rest of the entire problem.
0
 
LVL 96

Expert Comment

by:Bob Learned
ID: 24219613
1) I don't care about points--never have.

2) You can leave this question open for 21 days without comments--sometimes longer--before it shows up on cleanup process' radar.

3) If you got a solution that you had problems implementing, we can keep going, as long as you wish.

4) If you didn't find a solution, just delete this question.
0
 
LVL 1

Author Comment

by:JB4375
ID: 24414889
I thought about this for a while and still not sure how to address this issue, so maybe it would be easier to change direction. What if, instead of using the edit function, the user would submit the information through the form?
In the event of a dupilcate, notify the user: Duplicate dept ID was entered. Continue?Yes/No.
No: Exit. Notify User that no change was made.
Yes: Overwrite the existing row with the new data. Notify user that the database updated successfully.
So I guess the question is the same.... how would I stipulate the specific row to be updated?
Thanks.
 
 
 
0
 
LVL 96

Expert Comment

by:Bob Learned
ID: 24415771
"how would I stipulate the specific row to be updated"

If you are trying to use the RowEditing event handler, then e.NewEditIndex is passed in the event arguments (GridViewEditEventArgs), that indicates the row the you need to edit.
0
 
LVL 1

Author Comment

by:JB4375
ID: 24425924
Ok... can you show me how to handle to handle this Row Editing event? Quite frankly this "piece of the puzzle" is over my head, and I'm at a loss at this point. Further, My previous suggestion was more or less an attempt at work around approach.
 
 
0
 
LVL 96

Expert Comment

by:Bob Learned
ID: 24426063
I thought that I gave you a way.  Did that example not help?


Protected Sub EmployeeGridView_RowEditing(ByVal sender As Object, _
                                              ByVal e As System.Web.UI.WebControls.GridViewEditEventArgs) _
                                              Handles EmployeeGridView.RowEditing
        ' Get the info about the edited row
        Dim employeeID As String = EmployeeGridView.Rows(e.NewEditIndex).Cells(1).Text
        Dim firstName As String = EmployeeGridView.Rows(e.NewEditIndex).Cells(2).Text
        Dim lastName As String = EmployeeGridView.Rows(e.NewEditIndex).Cells(3).Text
    End Sub

Open in new window

0
 
LVL 1

Author Comment

by:JB4375
ID: 24454330
Right.... but the edit works, and the update works, so wouldn't  you want to handle it on the update event? I was looking at something like the code below.  
At first I was playing with a variation of the NewEdit Index above:

Sub GridView1_RowUpdated(ByVal sender As Object, ByVal e As GridViewUpdatedEventArgs)
Dim Submitted As Date = GridView1.Rows(e.AffectedRows).Cells(12).Text
Dim Requestor As String = GridView1.Rows(e.AffectedRows).Cells(13).Text
Then I thought maybe was thinking I could insert through SQL as indicated below, however it's not updating the requestor and submitted fields in either case.
 


 
 
  Sub GridView1_RowUpdated(ByVal sender As Object, ByVal e As GridViewUpdatedEventArgs)
 
        Dim sConn As Data.SqlClient.SqlConnection
        Dim sComm As Data.SqlClient.SqlCommand
        Dim sAdapt As Data.SqlClient.SqlDataAdapter
 
        sConn = New Data.SqlClient.SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings("MyConnection").ConnectionString)
        sComm = New Data.SqlClient.SqlCommand("INSERT INTO Automated_ZM_Dept_Request (Submitted, Requestor) VALUES ('" & strDate & "','" & strUser & "')", sConn)
        sAdapt = New Data.SqlClient.SqlDataAdapter(sComm)
        sConn.Open()
        sComm.ExecuteNonQuery()
        sConn.Close()
        lblResults.Visible = True
        imgCheckMark.Visible = True
        imgRedX.Visible = False
        lblResults.Text = "Row Successfully Updated"
        clrFields()
        GridView1.DataBind()
 
    End Sub

Open in new window

0
 
LVL 96

Expert Comment

by:Bob Learned
ID: 24454364
This question has been open for a while, so remind me about what you are really asking for (too much context switching is confusing).
0
 
LVL 1

Author Comment

by:JB4375
ID: 24456198
Sorry about that.... Ok... so the grid displays the contents of the SQL table. It's using the built in edit feature. I can select edit on any row, change the info, select update, and it takes.
All the edit feature does is "open" the fields of the grid so that they can be edited, but nothing happens until you click update.
When that occurs I want to update the "Submitted"  and "Requestor" columns with strdate and strUser on that row. So it made sense, to me anyway, to "On Update" event, establish a SQL connection, and insert those values into the table using something similar to the code in the code block above.
You would need to specify which row needed to be upated. I thought these lines would outline it:
Dim Submitted As Date = GridView1.Rows(e.AffectedRows).Cells(12).Text
Dim Requestor As String = GridView1.Rows(e.AffectedRows).Cells(13).Text  
But it seems the way it's laid out in this fashion that it's actually grabbing what's already in these two cells, rather than updating them.
 Does that help?
 
0
 
LVL 96

Accepted Solution

by:
Bob Learned earned 2000 total points
ID: 24456574
Does this give you any ideas why you can't use the AffectedRows?

GridViewUpdatedEventArgs.AffectedRows Property
http://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.gridviewupdatedeventargs.affectedrows(VS.80).aspx

"Gets the number of rows affected by the update operation."

And, here:

GridViewUpdatedEventArgs.OldValues Property
http://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.gridviewupdatedeventargs.oldvalues(VS.80).aspx

DisplayValues(CType(e.NewValues, OrderedDictionary), CType(e.OldValues, OrderedDictionary))
0
 
LVL 1

Author Closing Comment

by:JB4375
ID: 31594233
TLO,
This project has been pushed to the back burner. Too many other things going on with accounts creations, and other pet projects. I'm going to continue to play with it in the mean time. Thanks for all your helpful suggestions.
0

Featured Post

Become an Android App Developer

Ready to kick start your career in 2018? Learn how to build an Android app in January’s Course of the Month and open the door to new opportunities.

Question has a verified solution.

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

Just a quick little trick I learned recently.  Now that I'm using jQuery with abandon in my asp.net applications, I have grown tired of the following syntax:      (CODE) I suppose it just offends my sense of decency to put inline VBScript on a…
Introduction This article shows how to use the open source plupload control to upload multiple images. The images are resized on the client side before uploading and the upload is done in chunks. Background I had to provide a way for user…
this video summaries big data hadoop online training demo (http://onlineitguru.com/big-data-hadoop-online-training-placement.html) , and covers basics in big data hadoop .
Enter Foreign and Special Characters Enter characters you can't find on a keyboard using its ASCII code ... and learn how to make a handy reference for yourself using Excel ~ Use these codes in any Windows application! ... whether it is a Micr…
Suggested Courses
Course of the Month15 days, 2 hours left to enroll

577 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