Solved

EDITTING IN GRIDVIEW HELP

Posted on 2006-07-05
29
760 Views
Last Modified: 2012-06-21

Hello:

My question is for anyone that can assist me with this little dilemma I am encountering.  I have this ASP.net website that I have created in Visual Web Developer, and in this website i have a search function that when a user types in the required field in a textbox, it will pull up the record set in a gridview.  I do not have this Gridview populate until the user presses the lookup button, and then in code i have attached this gridview to populate for the persons request.  

This seems to work just fine, where the dilemma comes to play is that I would like for the user to have the option to edit the recordset that was brought up.  I was hoping someone can help me with this task..  I  appreciate everyones help.
 
0
Comment
Question by:JWFreedom
  • 16
  • 13
29 Comments
 
LVL 14

Expert Comment

by:Ramuncikas
ID: 17046562
0
 

Author Comment

by:JWFreedom
ID: 17050024
Ive checked this site once before, but this only portrays a databound gridview.  My gridview is not databound until the lookup button is pressed hich binds the data in the grid via VB coding in the background.  Was hoping someone knows how to bind the edit fields.  

Thanks in advanced,

Chad
0
 
LVL 14

Expert Comment

by:Ramuncikas
ID: 17052887
Well, then could you please explain why this sample is not suitable? You say that it shows how to edit a databound grid and yours in only bound after a "lookp" button is pressed. So you mean that you'd like to edit something in your grid untill "lookup" is pressed? Or I understand you wrong?
0
 

Author Comment

by:JWFreedom
ID: 17053740
yeah,, the grid isn't shown until the lookup button is pressed, so I am actually getting the recordset as soon as this Lookup button set is pressed.  I need to manually code the edit field, but have no idea where to begin,,

Thanks in advanced,

Chad
0
 

Author Comment

by:JWFreedom
ID: 17061098
Can anyone help me with this issue...
0
 
LVL 14

Expert Comment

by:Ramuncikas
ID: 17061620
Could you tell me when do you want to edit? Before grid is filled with data or after?
0
 

Author Comment

by:JWFreedom
ID: 17073891
I want to thank you for your time so far,  I have trying different tacktics and nothing seems to do want I want.  

I woud want the user to have the choice to edit, just as the feature if using the edit in the application.  After the data has been brought up.  

Here is how it is currently setup:

Enter Employees Last Name: [ type text here  ]     (user types in last name)  
                                                   <LOOKUP> (button pressed after last name)

{Gridview with data Record for specific employee}  (shows up after the <LOOKUP> button is pressed.)

Want to be able to edit the record if need be, to all records that are in search of. For instance, how I would like it to function:

Enter Employees Last Name: [ type text here  ]     (user types in last name)  
                                                   <LOOKUP> (button pressed after last name)

<Edit>{Gridview with data Record for specific employee}  (shows up after the <LOOKUP> button is pressed.)
      <Update> <Cancel> [ record to edit ]

 Once <update> is pressed, the recordset will be inputted in SQL with the appropriate update.  Maybe including a messagebox, with OK, CANCEL, asking if sure to update, once the update has been pressed.  And if sure they would press the OK button on the message box, sending the recordset to SQL.

The messagebox is that important as the acctual edit format.  I greatly appreciate your help so far.

Regards,

Chad

0
 

Author Comment

by:JWFreedom
ID: 17073916
I forgot to mention that once Edit is pressed, it would bring up the recordset in the edit view, with the textboxes.
0
 

Author Comment

by:JWFreedom
ID: 17073930
The messagebox isn't that important as the acctual edit format.  I mistyped from before.
0
 
LVL 14

Expert Comment

by:Ramuncikas
ID: 17075734
So what is whong with the link a posted above? There is a detailed guide how to setup your gridview for data editing and of course updating. If you prepare your gridveiw for editing/updating at design time but do not bind it to any datasource then there will be no editing possibility until you do databinding. So the above link does not fault your page's logic.

Well, on the other hand I myself never trusted controls/components like SqlDatasource. All of my databinding, selecting, updating and deleting I always do in a kind of manual way. All I have to do is add a template column, add there buttons for editing, updating canceling and deleting, set their CommandName and CommandArgument properties and then listen to ItemCommand event. It's all about datagrid but still... I like to be in control of processed happening on my pages... Well, as much as I am able to be :)
0
 
LVL 14

Expert Comment

by:Ramuncikas
ID: 17075747
Sorry for typos
0
 

Author Comment

by:JWFreedom
ID: 17076670
Im not sure where to go from your previous comment.  In the example from the link you previously posted, they are using c++ coding where I am using VB, so i am not sure what to do about that.
0
 

Author Comment

by:JWFreedom
ID: 17076794
Was hoping if you had any ideas, as in coding, here the VB code for the LOOKUP BUTTON:

    Protected Sub Button4_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles Button4.Click
   
  ' When ' is entered in the textbox, invalid syntax erro occurs, Messagebox shows up now informs invalid character  
 If TextBox1.Text = "'" Then
            MessageBox.Show("Not Proper Character")
            MessageBox.Show("Please Re-Enter Field")
            TextBox1.Text = ""
            Stop
        Else

            If TextBox1.Text = "" Then 'Displays message when button is click with blank textbox
                MessageBox.Show("Please Type in Last Name")
            Else
                If TextBox1.Text = "" Then 'clears the textbox
                    Stop
                Else

                    Dim dbconn, dbcomm, sql, dbread, name
                    name = TextBox1.Text

                    dbconn = New Data.OleDb.OleDbConnection("Provider=SqloleDB;Data Source=FTCPCHS93951;Initial Catalog=INVENTORY;Persist Security Info=True;User ID=sa")
                    dbconn.Open() 'open DB connection

                    'sql = "SELECT * FROM INVENTORY where Employee like '" & name & "%'" 'create sql query
                    sql = "SELECT Employee as [Employee Name], PC_Name as [Computer Name on Domain], PC_Type as [Type of Computer], PC_Model as [Computer Make and Model], Service_Tag_ID as [Service Tag ID], Express_Service_Code as [Express Service Code], Warranty_Status as [Warranty Status in Days] FROM INVENTORY where Employee like '" & name & "%'" 'create sql query

                    dbcomm = New Data.OleDb.OleDbCommand(sql, dbconn)     'create command
                    dbread = dbcomm.ExecuteReader() 'get query results

                    GridView2.DataSource = dbread 'set datagrid source and databind
                    GridView2.DataBind()
                    dbread.close()
                    dbconn.close()
                   
                    If GridView2.Visible = False Then
                        GridView2.Visible = True

                    End If
                End If
            End If
        End If
        If GridView2.Visible = True And TextBox1.Text = "" Then
            GridView2.Visible = False
        End If
        ' Display Messagebox when no records are found
        If GridView2.PageCount = 0 Then
            MessageBox.Show("No Entry Found")
        End If

        ' Clears the textbox from previous entry if no record is found
        If GridView2.PageCount = 0 Then
            TextBox1.Text = ""
        Else
            If GridView2.PageCount = 0 = False Then
                TextBox1.Text = ""

            End If
        End If
0
 
LVL 14

Expert Comment

by:Ramuncikas
ID: 17077238
Actually there is not a C++, it's a C# :) But if you'd be more carefull you'd notice that there is a VB code too.
Here are some other links illustrating how to do data editing with a gridview:
http://www.asp.net/QUICKSTART/aspnet/doc/ctrlref/data/gridview.aspx
http://www.exforsys.com/content/view/1651/354/
0
Threat Intelligence Starter Resources

Integrating threat intelligence can be challenging, and not all companies are ready. These resources can help you build awareness and prepare for defense.

 

Author Comment

by:JWFreedom
ID: 17081248
Yeah,, these links are not what im looking for, they all are indicating that I should set up a datalink through Design View but the way my code is set up, the datalink is setup through VB coding, so editting in the Design view doesn't work for this situation.  Im not sure exactly the difference between C++ and C# but any who, I need to know the coding behind the EDIT part in VB.

Thanks So far,

Chad
 
0
 
LVL 14

Expert Comment

by:Ramuncikas
ID: 17081682
Ok.
#1. Set up your GridView:
 - add bound columns
 - add template column

#2. Set up template column:
 - in the item template add a button called cedit, set it's CommandName property to cmdEdit and bind it's CommandArgument property to record's ID
 - in the EditItemTemplate add buttons cmdSave and cmdCancel. Set their ComandName properties Save and Cancel respectively. Bind  their CommandArgument properties to record's IDs

#3. Move your databinding code to a separate Sub like GetMyData. In your case it would be:
Private Sub GetMyData(ByVal Criteria as string)
Dim dbconn, dbcomm, sql, dbread

                    dbconn = New Data.OleDb.OleDbConnection("Provider=SqloleDB;Data Source=FTCPCHS93951;Initial Catalog=INVENTORY;Persist Security Info=True;User ID=sa")
                    dbconn.Open() 'open DB connection

                    'sql = "SELECT * FROM INVENTORY where Employee like '" & name & "%'" 'create sql query
                    sql = "SELECT Employee as [Employee Name], PC_Name as [Computer Name on Domain], PC_Type as [Type of Computer], PC_Model as [Computer Make and Model], Service_Tag_ID as [Service Tag ID], Express_Service_Code as [Express Service Code], Warranty_Status as [Warranty Status in Days] FROM INVENTORY where Employee like '" & Criteria & "%'" 'create sql query

                    dbcomm = New Data.OleDb.OleDbCommand(sql, dbconn)     'create command
                    dbread = dbcomm.ExecuteReader() 'get query results

                    GridView2.DataSource = dbread 'set datagrid source and databind
                    GridView2.DataBind()
                    dbread.close()
                    dbconn.close()
                   
                    If GridView2.Visible = False Then
                        GridView2.Visible = True

                    End If
End sub

#4. Write code for gridview's rowcommad event:
Protected Sub GridView1_RowCommand(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewCommandEventArgs) Handles GridView1.RowCommand
        Dim _row As GridViewRow
        _row = CType(e.CommandSource.parent.parent, GridViewRow)

        Select Case e.CommandName
            Case "cmdEdit"
                Me.GridView1.EditIndex = _row.RowIndex
                GetMyData(<criteria here>)
            Case "Save"
                'database updating steps here
                 GetMyData(<criteria here>)
            Case "cmdCancel"
                Me.GridView1.EditIndex = -1
                GetMyData(<criteria here>)
        End Select
    End Sub

Hope this could be a hint of what you have to do
There are other ways to achieve same results but this is the way I do things like that
0
 

Author Comment

by:JWFreedom
ID: 17082075
what is records ID?
0
 

Author Comment

by:JWFreedom
ID: 17082120
Thanks by the way, I believe this is what I am looking for...
0
 
LVL 14

Expert Comment

by:Ramuncikas
ID: 17082237
It's a nice practice to have a column in a table whitch uniquely identifies records and these columns are often of some numeric type. These columns are often called ID. For example:

Table "Users"
ID   UserName   Name     LastName
-------------------------------------------------
1    JohnDoe     John      Doe
2    Marry          Marry     Smith
...
45  Anthony      Anthony Parker

That's what I ment by "record IDs"
0
 

Author Comment

by:JWFreedom
ID: 17082349
A couple of questions for you:

How do I Bind the Edit, Update and Cancel to their CommandArugment to record's IDs

What criteria must i have inside the GetMyData(" ") for each of the Cases

THANK YOU SO MUCH FOR YOUR HELP>>>>
0
 
LVL 14

Expert Comment

by:Ramuncikas
ID: 17082806
>>> How do I Bind the Edit, Update and Cancel to their CommandArugment to record's IDs
A little preface: you need this for further steps of your code. Especialy in Case "cmdSave" (sorry, mistake in my sample code - there SHOULD BE Case "cmdSave" not Case "Save"). In that block you can reference e.CommandArgument and build your UPDATE sql string to update database.

Right-click on Edit button and select "Edit DataBindings..."
When window opens
       in Bindable properties select CommandArgument
       in Code Expression field enter Eval("MyIDColumnName")  (change MyIDColumnName to your column name of ID column)
Click OK.
Congratulations - you have bint Edit button's CommandArgument property to datasource's column :)

>>> What criteria must i have inside the GetMyData(" ") for each of the Cases
This should be a value from a textbox. Pay attention to  your SQL string's FROM clause. I've changed your variable "name" with my variable "Criteria". This way whatever you pass to GetMyData sub you get a recordset filtered by a value you pass.

By the way as you can see all code in GetMyData sub is copied from your Sub Button4_Click. So your code in Sub Button4_Click should look like this now:
  Protected Sub Button4_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles Button4.Click
   
  ' When ' is entered in the textbox, invalid syntax erro occurs, Messagebox shows up now informs invalid character  
 If TextBox1.Text = "'" Then
            MessageBox.Show("Not Proper Character")
            MessageBox.Show("Please Re-Enter Field")
            TextBox1.Text = ""
            Stop
        Else

            If TextBox1.Text = "" Then 'Displays message when button is click with blank textbox
                MessageBox.Show("Please Type in Last Name")
            Else
                If TextBox1.Text = "" Then 'clears the textbox
                    Stop
                Else
                   'So little left??? Yes!!!
                   GetMyData(TextBox1.Text)
                End If
            End If
        End If
        If GridView2.Visible = True And TextBox1.Text = "" Then
            GridView2.Visible = False
        End If
        ' Display Messagebox when no records are found
        If GridView2.PageCount = 0 Then
            MessageBox.Show("No Entry Found")
        End If

        ' Clears the textbox from previous entry if no record is found
        If GridView2.PageCount = 0 Then
            TextBox1.Text = ""
        Else
            If GridView2.PageCount = 0 = False Then
                TextBox1.Text = ""

            End If
        End If
End sub ' you missed that :)

And finaly some more notes about your code I didn't write yesterday (was late enough to go to bed):
*
When you declare variables don't just write their name but declare their type too.
Dim dbconn, dbcomm, sql, dbread, name 'this is a bad manner
Dim dbconn AS Data.Oledb.OledbConnaction 'This is a good manner
*
When declaring variables capitalize meaningfull parts of their names. This way you'll get a more readable code:
Dim dbconn ... 'not very eye-catching, uh?
Dim dbConn... 'hey, I know what this variable is about :)
*
Don't leave default names of controls on a page even if you have two of them. Noone wants to write comments and noone is able to remember everything. From your Sub Button4_Click I suppose you have four buttons on your page. I bet NOW (at this moment when you are reading this) you don't know what a Button2 does (and if you DO know that means you spend too much time in front of your code beacause of reasons mentioned above :) ) Imagine that after half a year of a successful functioning of your page you'll have to make some improvements. Will it be easier to remember what Button4 is on your page for or will it be easier to remember what cmdSearch button is for? :) And what if your page has 4 combos 3 gridviews and 15 checkboxes? :) I hope you got the point.

That's it for now
0
 

Author Comment

by:JWFreedom
ID: 17090777
I have two issues now,, First issue is that everytime I click the edit button when the record is pulled, the gridview disappears until I click the lookup button again, then the gridview will display in the edit format

Second issue,  what are the   'database updating steps

Thanks so much,, you are totally right about the whole naming scheme.  This acctually is just a tool for myself and another associate to use to help with Electronic Inventory.   You have been really helpful,, I am just an newbie when it comes to ASP.net, as well as VB coding.  I dabbled in it in college but forgot alot.  Thanks again,, Yoou are the MAN....
0
 
LVL 14

Expert Comment

by:Ramuncikas
ID: 17091692
>>> ... everytime I click the edit button when the record is pulled, the gridview disappears
Could you post you Gridview_RowCommand event code. I hope only then I could tell you the reason

>>> ... what are the   'database updating steps
Well, you have code where you declare and initialize connection, command and execute sql string. The same way you should update your database with new values, but this time sql string would be like "UPDATE MyTable SET ..."
0
 

Author Comment

by:JWFreedom
ID: 17092909
Here is my GridView_RowCommand code:
 
Protected Sub GridView2_RowCommand(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewCommandEventArgs) Handles GridView2.RowCommand

        Dim _row As GridViewRow
        _row = CType(e.CommandSource.parent.parent, GridViewRow)

        Select Case e.CommandName

            Case "cmdEdit" 'binds the editting in gridview2
                Me.GridView2.EditIndex = _row.RowIndex
                GetMyData("SELECT ID as [ID], Employee as [Employee Name], PC_Name as [Computer Name on Domain], PC_Type as [Type of Computer], PC_Model as [Computer Make and Model], Service_Tag_ID as [Service Tag ID], Express_Service_Code as [Express Service Code], Warranty_Status as [Warranty Status in Days] FROM INVENTORY")

            Case "cmdUpdate" 'updates the SQL table
                Dim sqlConn As Data.SqlClient.SqlConnection = New Data.SqlClient.SqlConnection("Provider=SqlOLEdb;Data Source=FTCPCHS93951;Initial Catalog=INVENTORY;Persist Security Info=True;User ID=sa")

                Dim sqlInventory As Data.SqlClient.SqlDataAdapter = New Data.SqlClient.SqlDataAdapter("SELECT ID as [ID], Employee as [Employee Name], PC_Name as [Computer Name on Domain], PC_Type as [Type of Computer], PC_Model as [Computer Make and Model], Service_Tag_ID as [Service Tag ID], Express_Service_Code as [Express Service Code], Warranty_Status as [Warranty Status in Days] FROM INVENTORY", sqlConn)

                Dim inventoryCommandBuilder As Data.SqlClient.SqlCommandBuilder = New Data.SqlClient.SqlCommandBuilder(sqlInventory)

                'sqlInventory.Update(<not sure what to pace her>)

                GetMyData("UPDATE [INVENTORY] SET [Employee] = @Employee, [PC_Name] = @PC_Name, [PC_Type] = @PC_Type, [PC_Model] = @PC_Model, [Service_Tag_ID] = @Service_Tag_ID, [Express_Service_Code] = @Express_Service_Code, [Warranty_Status] = @Warranty_Status, WHERE [ID] = @ID")

            Case "cmdCancel"
                Me.GridView2.EditIndex = -1
                GetMyData("SELECT ID as [ID], Employee as [Employee Name], PC_Name as [Computer Name on Domain], PC_Type as [Type of Computer], PC_Model as [Computer Make and Model], Service_Tag_ID as [Service Tag ID], Express_Service_Code as [Express Service Code], Warranty_Status as [Warranty Status in Days] FROM INVENTORY")
        End Select
    End Sub
0
 
LVL 14

Expert Comment

by:Ramuncikas
ID: 17093899
Wow, seems like you misunderstood me (or I misunderstood you).

The point of GetMyData sub's parameter was to pass a filter criteria ONLY and put it into SELECT statement's WHERE clause. Calling GetMyData("Tomas") should execute SELECT * FROM Users WHERE UserName = 'Tomas' (it's jus a sample). If you pass entire SQL statement then some day you will fall into dificulties when your SELECT statement will change. Coding this way you will have to change your SQL statement in ...(counting)...three places instead of one. You will or will not change this it's up to you.

Now I don't see that your SELECT statemen would contain any WHERE criteria. WHY? You said that you have to retrieve records according to the textbox's text. I think you should change this. (I told you, didn't I? :))

A bit about the databinding logic. Everytime a page loads gridview has to get data to show. That is what GetMyData sub  should do. Calling GetMyData with UPDATE statement will give you no result as UPDATE statement returns no records. Every click in your page should bind you gridview to records, that is every time you have to call GetMyData where you execute the SELECT statement and bind results to gridview. The only difference between clicks is that you prepare grid for something. Like:
Case "cmdEdit"
    'tell gridview what row should go into edit mode
    'execute select and bind to gridview
Case "cmdUpdate"
   'uhu, user entered new values and wants to update? ok!
   'prepare UPDATE statement, that is:
      'get new values
      'put them into UPDATE statement
   'execute update statemeny (here database gets updated, but not gridview itself)
   'tell gridview that none of the rows will be in edit mode
   'again! execute select and bind to gridview (it is HERE where gridview will show record with updates because database is updated already)
Case "cmdCancel"
   'user does not want to update? ok!
   'tell gridview that none of the rows will be in edit mode
   'again! execute select and bind to gridview

You see each time your page reloads (no matter what caused this) gridview (and any other databound control) looses it's data, so on every reload you have to open connection, select records and bind them to gridview (and again - or any other databound control). Things become more easier when you dedicate one sub for this purpose (GetMyData in this case).

One more thing - is there any code in a Page_Load event that modifies any gridview properties? Could you post the code of event here?
0
 

Author Comment

by:JWFreedom
ID: 17094074
Here is the entire code, it is a little sloppy, but it works for the jist of things...  Remember, the data is being bounded already by a button4_click, so I do not need to have the edit_click bind the record, because the record is already bound before editting.  I just need the option to where the user might want to edit the recordset, he has the opportunity within this search function, rather than scrolling to search for the recordset in the entire gridview, which I have as an option.


Partial Class _Default
    Inherits System.Web.UI.Page

    Protected Sub Button1_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles Button1.Click
        GridView1.DataBind()

        ' Makes the Boxes not Visible when Button is clicked
        DetailsView1.Visible = False
        '   Label1.Visible = False
        Panel1.Visible = False

        ' Messagebox comes up if button is pressed again
        If GridView1.Visible Then
            MessageBox.Show("Grid Already in View")
        Else
            If GridView1.Visible = False Then
                GridView1.Visible = True
            End If
        End If


        '        If Label2.Visible = False Then
        'Label2.Visible = True
        ' End If



    End Sub
    Protected Sub Button2_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles Button2.Click

        ' Makes the Boxes not Visible when Button is clicked
        GridView1.Visible = False
        'Label2.Visible = False
        Panel1.Visible = False

        ' Messagebox comes up if button is pressed again
        If DetailsView1.Visible Then
            MessageBox.Show("Insert Already in View")
        Else
            If DetailsView1.Visible = False Then
                DetailsView1.Visible = True
            End If
        End If

        'If Label1.Visible = False Then
        'Label1.Visible = True
        'End If



    End Sub
    Protected Sub Button3_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles Button3.Click

        'Hides the gridview
        GridView2.Visible = False

        'Clears the textbox upon view
        TextBox1.Text = ""

        ' Makes the Boxes not Visible when Button is clicked
        GridView1.Visible = False
        'Label2.Visible = False
        ' Label1.Visible = False
        DetailsView1.Visible = False

        ' Messagebox comes up if button is pressed again
        If Panel1.Visible = True Then
            MessageBox.Show("Search Already in View")
        Else
            If Panel1.Visible = False Then
                Panel1.Visible = True

            End If
        End If

    End Sub
    Private Sub GetMyData(ByVal Criteria As String)
        Dim dbconn, dbcomm, sql, dbread


        dbconn = New Data.OleDb.OleDbConnection("Provider=SqloleDB;Data Source=FTCPCHS93951;Initial Catalog=INVENTORY;Persist Security Info=True;User ID=sa")
        dbconn.Open() 'open DB connection

        sql = "SELECT ID as [ID], Employee as [Employee Name], PC_Name as [Computer Name on Domain], PC_Type as [Type of Computer], PC_Model as [Computer Make and Model], Service_Tag_ID as [Service Tag ID], Express_Service_Code as [Express Service Code], Warranty_Status as [Warranty Status in Days] FROM INVENTORY where Employee like '" & Criteria & "%'" 'create sql query

        dbcomm = New Data.OleDb.OleDbCommand(sql, dbconn)     'create command
        dbread = dbcomm.ExecuteReader() 'get query results

        GridView2.DataSource = dbread 'set datagrid source and databind
        GridView2.DataBind()
        dbread.close()
        dbconn.close()

        If GridView2.Visible = False Then
            GridView2.Visible = True

        End If
    End Sub

    Protected Sub Button4_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles Button4.Click
        If TextBox1.Text = "'" Then
            MessageBox.Show("Not Proper Character")
            MessageBox.Show("Please Re-Enter Field")
            TextBox1.Text = ""
            Stop
        Else

            If TextBox1.Text = "" Then 'Displays message when button is click with blank textbox
                MessageBox.Show("Please Type in Last Name")
            Else
                If TextBox1.Text = "" Then 'clears the textbox
                    Stop
                Else
                    Dim dbconn, dbcomm, sql, dbread, name
                    name = TextBox1.Text

                    dbconn = New Data.OleDb.OleDbConnection("Provider=SqlOLEdb;Data Source=FTCPCHS93951;Initial Catalog=INVENTORY;Persist Security Info=True;User ID=sa")
                    dbconn.Open() 'open DB connection

                    'sql = "SELECT * FROM INVENTORY where Employee like '" & name & "%'" 'create sql query
                    sql = "SELECT ID as [ID], Employee as [Employee Name], PC_Name as [Computer Name on Domain], PC_Type as [Type of Computer], PC_Model as [Computer Make and Model], Service_Tag_ID as [Service Tag ID], Express_Service_Code as [Express Service Code], Warranty_Status as [Warranty Status in Days] FROM INVENTORY where Employee like '" & name & "%'" 'create sql query

                    dbcomm = New Data.OleDb.OleDbCommand(sql, dbconn)     'create command
                    dbread = dbcomm.ExecuteReader() 'get query results

                    GridView2.DataSource = dbread 'set datagrid source and databind
                    GridView2.DataBind()
                    dbread.close()
                    dbconn.close()

                End If
                ' TextBox1.Text = ""
                If GridView2.Visible = False Then
                    GridView2.Visible = True

                End If
            End If
        End If

        If GridView2.Visible = True And TextBox1.Text = "" Then
            GridView2.Visible = False
        End If
        ' Display Messagebox when no records are found
        If GridView2.PageCount = 0 Then
            MessageBox.Show("No Entry Found")
        End If

        ' Clears the textbox from previous entry if no record is found
        If GridView2.PageCount = 0 Then
            TextBox1.Text = ""
            ' Else
            '  If GridView2.PageCount = 0 = False Then
            'TextBox1.Text = ""

        End If
        'End If




    End Sub

    Protected Sub GridView2_RowCommand(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewCommandEventArgs) Handles GridView2.RowCommand


        Dim _row As GridViewRow
        _row = CType(e.CommandSource.parent.parent, GridViewRow)

        Select Case e.CommandName

            Case "cmdEdit"
                Me.GridView2.EditIndex = _row.RowIndex
                GetMyData("SELECT ID as [ID], Employee as [Employee Name], PC_Name as [Computer Name on Domain], PC_Type as [Type of Computer], PC_Model as [Computer Make and Model], Service_Tag_ID as [Service Tag ID], Express_Service_Code as [Express Service Code], Warranty_Status as [Warranty Status in Days] FROM INVENTORY")

            Case "cmdUpdate"
                Dim sqlConn As Data.SqlClient.SqlConnection = New Data.SqlClient.SqlConnection("Data Source=FTCPCHS93951;Initial Catalog=INVENTORY;Persist Security Info=True;User ID=sa")
                Dim sqlInventory As Data.SqlClient.SqlDataAdapter = New Data.SqlClient.SqlDataAdapter("SELECT ID as [ID], Employee as [Employee Name], PC_Name as [Computer Name on Domain], PC_Type as [Type of Computer], PC_Model as [Computer Make and Model], Service_Tag_ID as [Service Tag ID], Express_Service_Code as [Express Service Code], Warranty_Status as [Warranty Status in Days] FROM INVENTORY", sqlConn)
                Dim inventoryCommandBuilder As Data.SqlClient.SqlCommandBuilder = New Data.SqlClient.SqlCommandBuilder(sqlInventory)

                ' sqlInventory.Update("GetMyData")


                'database updating steps here
                GetMyData("UPDATE [INVENTORY] SET [Employee] = @Employee, [PC_Name] = @PC_Name, [PC_Type] = @PC_Type, [PC_Model] = @PC_Model, [Service_Tag_ID] = @Service_Tag_ID, [Express_Service_Code] = @Express_Service_Code, [Warranty_Status] = @Warranty_Status, WHERE [ID] = @ID")

            Case "cmdCancel"
                Me.GridView2.EditIndex = -1
                GetMyData("SELECT ID as [ID], Employee as [Employee Name], PC_Name as [Computer Name on Domain], PC_Type as [Type of Computer], PC_Model as [Computer Make and Model], Service_Tag_ID as [Service Tag ID], Express_Service_Code as [Express Service Code], Warranty_Status as [Warranty Status in Days] FROM INVENTORY")
        End Select
    End Sub

    Protected Sub LinkButton1_Click(ByVal sender As Object, ByVal e As System.EventArgs)
        GridView2.Visible = True

    End Sub
End Class
Public Class MessageBox
    Private Shared m_executingPages As New Hashtable()


    Private Sub New()
    End Sub 'New

    Public Shared Sub Show(ByVal sMessage As String)
        ' If this is the first time a page has called this method then
        If Not m_executingPages.Contains(HttpContext.Current.Handler) Then
            ' Attempt to cast HttpHandler as a Page.
            Dim executingPage As Page = HttpContext.Current.Handler '
            'ToDo: Error processing original source shown below
            '
            '
            '--------------------------------------------------------^--- Syntax error: ';' expected

            If Not (executingPage Is Nothing) Then
                ' Create a Queue to hold one or more messages.
                Dim messageQueue As New Queue()

                ' Add our message to the Queue
                messageQueue.Enqueue(sMessage)

                ' Add our message queue to the hash table. Use our page reference
                ' (IHttpHandler) as the key.
                m_executingPages.Add(HttpContext.Current.Handler, messageQueue)

                ' Wire up Unload event so that we can inject
                ' some JavaScript for the alerts.
                AddHandler executingPage.Unload, AddressOf ExecutingPage_Unload
            End If
        Else
            ' If were here then the method has allready been
            ' called from the executing Page.
            ' We have allready created a message queue and stored a
            ' reference to it in our hastable.
            Dim queue As Queue = CType(m_executingPages(HttpContext.Current.Handler), Queue)

            ' Add our message to the Queue
            queue.Enqueue(sMessage)
        End If
    End Sub 'Show

    ' Our page has finished rendering so lets output the
    ' JavaScript to produce the alert's
    Private Shared Sub ExecutingPage_Unload(ByVal sender As Object, ByVal e As EventArgs)
        ' Get our message queue from the hashtable
        Dim queue As Queue = CType(m_executingPages(HttpContext.Current.Handler), Queue)

        If Not (queue Is Nothing) Then
            Dim sb As New StringBuilder()

            ' How many messages have been registered?
            Dim iMsgCount As Integer = queue.Count

            ' Use StringBuilder to build up our client side JavaScript.
            sb.Append("<script language='javascript'>")

            ' Loop round registered messages
            Dim sMsg As String
            While (iMsgCount > 0)
                iMsgCount = iMsgCount - 1
                sMsg = CStr(queue.Dequeue())
                sMsg = sMsg.Replace(ControlChars.Lf, "\n")
                sMsg = sMsg.Replace("""", "'")
                sb.Append("alert( """ + sMsg + """ );")
            End While
            ' Close our JS
            sb.Append("</script>")

            ' Were done, so remove our page reference from the hashtable
            m_executingPages.Remove(HttpContext.Current.Handler)

            ' Write the JavaScript to the end of the response stream.
            HttpContext.Current.Response.Write(sb.ToString())
        End If
    End Sub 'ExecutingPage_Unload
   
End Class 'MessageBox
0
 
LVL 14

Accepted Solution

by:
Ramuncikas earned 500 total points
ID: 17094586
>>> Remember, the data is being bounded already by a button4_click, so I do not need to have the edit_click bind the record, because the record is already bound before editting.

Wrong wrong wrong!!!
Web app is not the same as windows app. In simple words web app works like this: when app gets request to aspx page it creates an instance of your page class. There is Init event where all your controls are created and saigned default properties. Then comes Page_Load event. All code in that event is executed. Then if page is requested by a click of a button then button_click event is executed. After that your page's class instance is rendered to HTML and sent to your browser. When your browser gets all of HTML an instance of tour page's class is destroyed. Realy? YES! So that means no datasources, no records are remembered because the class ir not in memory any more. The only case you DO NOT have to rebind gridview to datasource is when 1. gridview does not change it's state during page execution (datasource, page number, colors, NOTHING) 2. gridview's enableviewstate property is set to true. In all other cases you DO have to rebind gridview to datasource.

Here is what you should change in you code:
#1. Sub Button4_Click
Comment or delete everything from line
   Dim dbconn, dbcomm, sql, dbread, name
to line
   dbconn.close()
and put
   GetMyData(TextBox1.Text)
right after the line
   dbconn.close()

#2. Sub GridView2_RowCommand "Case "cmdEdit"" part
Comment everything
Add
   Me.GridView2.EditIndex = _row.RowIndex
   GetMyData(TextBox1.text)

#3. Sub GridView2_RowCommand "Case "cmdCancel"" part
Comment everything
Add
   Me.GridView2.EditIndex = -1
   GetMyData(TextBox1.text)

#4.  Sub GridView2_RowCommand "Case "cmdUpdate"" part
Comment everything
add steps to update database:
   - construct the update statement
   - open nonnection, execute that update statement
and add
   Me.GridView2.EditIndex = -1
   GetMyData(TextBox1.text)  
0
 

Author Comment

by:JWFreedom
ID: 17099280
Thank you so much,, you have been really helpful.  I feel I am in the home stretch,  I just need to figure out how to  - construct the update statement
   - open nonnection, execute that update statement.  This is the part that I must try to investigate myself. Thanks again...
0
 
LVL 14

Expert Comment

by:Ramuncikas
ID: 17103732
You're welcome
Glad I could help
Good luck
0

Featured Post

How to improve team productivity

Quip adds documents, spreadsheets, and tasklists to your Slack experience
- Elevate ideas to Quip docs
- Share Quip docs in Slack
- Get notified of changes to your docs
- Available on iOS/Android/Desktop/Web
- Online/Offline

Join & Write a Comment

Today is the age of broadband.  More and more people are going this route determined to experience the web and it’s multitude of services as quickly and painlessly as possible. Coupled with the move to broadband, people are experiencing the web via …
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…
Get a first impression of how PRTG looks and learn how it works.   This video is a short introduction to PRTG, as an initial overview or as a quick start for new PRTG users.
Here's a very brief overview of the methods PRTG Network Monitor (https://www.paessler.com/prtg) offers for monitoring bandwidth, to help you decide which methods you´d like to investigate in more detail.  The methods are covered in more detail in o…

708 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

Need Help in Real-Time?

Connect with top rated Experts

13 Experts available now in Live!

Get 1:1 Help Now