none
Visual Basic: How to use data-grid view to open edit form RRS feed

  • Question

  • This question may have been asked before but I wasn't able to download the file in the answer. 

    So here it goes: 
    1) I'm trying to use the data grid view in a way where a user clicks on a row and that opens up an edit window. 
    2) This edit window will have all  information of the previously selected row ready for
    3) the user must not only be able to edit the information but also save it back into its Microsoft Access database



    Wednesday, June 28, 2017 1:19 PM

Answers

All replies

  • So you'll want to handle a mouse event (perhaps CellMouseDoubleClick) and in that event handler you'll create a new instance of your edit form, passing the selected data row.  You then display the edit form and it loads the row's field values into the appropriate controls.  When the user clicks OK on the edit form, you update the values in the row instance from the edit controls and then perform an update on the database.

    You'll need to begin coding the solution and then you can post back with any specific code you are having trouble with.


    Reed Kimble - "When you do things right, people won't be sure you've done anything at all"

    Wednesday, June 28, 2017 2:03 PM
    Moderator
  • Thank you for your answer!

    But how do I pass the values from the main form (with data grid view) to edit form?

    Wednesday, June 28, 2017 2:44 PM
  • Thank you for your answer!

    But how do I pass the values from the main form (with data grid view) to edit form?

    That depends on how you setup the Edit form.  Since a form designed specifically to edit a particular data row can't do its work without that data row, I would suggest setting up a parameter in the edit form's constructor.  You can then pass the instance of the data row when creating the edit form instance.

    If you do a quick search there are countless threads about passing data between forms.  There are numerous ways to do it and you'll want to choose one most appropriate to your needs.  Again, in this case, I suspect that is passing the datarow in the form constructor.


    Reed Kimble - "When you do things right, people won't be sure you've done anything at all"

    Wednesday, June 28, 2017 2:47 PM
    Moderator
  • Thank you for your answer!

    But how do I pass the values from the main form (with data grid view) to edit form?

    Hi

    Here is some code that may help. In this case, I am using a DGV on Form1 which is Cell select - if you are using Row select, you would need to adjust.

    This code is purely an example and contains little/no error checking.

    The Form1 has a Button which invokes the Form2 with the row of data from the selected (Cell) row and populates a set of textboxes.

    When Form2 is closed,it sets the original data in the Form1 DGV row to the new values (You would probably need a confimation MessageBox on Form2 before just updating the values).

    Any way, here is the Button sub for Form1

    EDIT: I note you want a user click (Double Click?) to invoke the edit Form- you would need to adjust for that (NOTE: a single click may not be the best choice as users navigate using this)

        ' this  button click on Form1
        Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
            ' in this case, I amusing a cell select DGV
            If DataGridView1.SelectedCells.Count < 1 Then Exit Sub
            Dim row As Integer = DataGridView1.SelectedCells(0).RowIndex
            Dim r As DataGridViewRow = DataGridView1.Rows(row)
            Dim nf As New Form2 With {.dr = r}
            nf.Show()
        End Sub

    and here is Form2 code

    Option Strict On
    Option Explicit On
    Public Class Form2
        Public Property dr As DataGridViewRow
        Private Sub Form2_Load(sender As Object, e As EventArgs) Handles MyBase.Load
            ' do something with the incoming row such as fill
            ' the controls on this form
            TextBox1.Text = dr.Cells(0).Value.ToString
            TextBox2.Text = dr.Cells(1).Value.ToString
            TextBox3.Text = dr.Cells(2).Value.ToString
            TextBox4.Text = dr.Cells(3).Value.ToString
            TextBox5.Text = dr.Cells(4).Value.ToString
        End Sub
        Private Sub Form2_FormClosing(sender As Object, e As FormClosingEventArgs) Handles Me.FormClosing
            ' when closing this form, change source row values
            dr.Cells(0).Value = TextBox1.Text
            dr.Cells(1).Value = TextBox2.Text
            dr.Cells(2).Value = TextBox3.Text
            dr.Cells(3).Value = TextBox4.Text
            dr.Cells(4).Value = TextBox5.Text
        End Sub
    End Class


    Regards Les, Livingston, Scotland


    • Edited by leshay Wednesday, June 28, 2017 3:32 PM
    Wednesday, June 28, 2017 3:29 PM
  • I have a code sample for this doing master-details yet if you focus on simple the master part (see screenshot of the page) this is one way of editing as you asked for. Granted it's not a simple example so keep this in mind.

    https://code.msdn.microsoft.com/Windows-forms-detail-view-89372f21?redir=0


    Please remember to mark the replies as answers if they help and unmark them if they provide no help, this will help others who are looking for solutions to the same or similar problem. Contact via my Twitter (Karen Payne) or Facebook (Karen Payne) via my MSDN profile but will not answer coding question on either.
    VB Forums - moderator
    profile for Karen Payne on Stack Exchange, a network of free, community-driven Q&A sites

    Wednesday, June 28, 2017 4:34 PM
    Moderator
  • Here are some code samples from the link I provided in my first reply. Granted there is no method to open the form via the mouse yet that is easy to do. When I wrote desktop apps 99 percent of users cared less about mouse and more about pressing enter.

        Private Sub MasterDataGridView_KeyDown(sender As Object, e As KeyEventArgs) Handles MasterDataGridView.KeyDown 
            If e.KeyData = Keys.Enter Then 
     
                e.Handled = True 
                EditCurrentCustomer() 
            End If 
        End Sub 
        ''' <summary> 
        ''' master BindingNavigator edit button click event 
        ''' </summary> 
        ''' <param name="sender"></param> 
        ''' <param name="e"></param> 
        Private Sub BindingNavigatorEditCustomer_Click(sender As Object, e As EventArgs) Handles MasterBindingNavigatorEditCustomer.Click 
            EditCurrentCustomer() 
        End Sub 
        ''' <summary> 
        ''' Point of entry for editing current customer from either 
        ''' a button on the BindingNavigator or pressing the enter key 
        ''' on the master DataGridView 
        ''' </summary> 
        Private Sub EditCurrentCustomer() 
            Dim CustomerRow As DataRow = CType(bsMaster.Current, DataRowView).Row 
            Dim f As New CustomerForm(False, StateInformation, CustomerRow) 
     
            Try 
                If f.ShowDialog() = DialogResult.OK Then 
                    Dim ops As New Operations 
                    If Not ops.UpdateCustomer(CustomerRow) Then 
                        MessageBox.Show($"Failed to update: {ops.ExceptionMessage}") 
                    End If 
                End If 
            Finally 
                f.Dispose() 
            End Try 
        End Sub 


    Please remember to mark the replies as answers if they help and unmark them if they provide no help, this will help others who are looking for solutions to the same or similar problem. Contact via my Twitter (Karen Payne) or Facebook (Karen Payne) via my MSDN profile but will not answer coding question on either.
    VB Forums - moderator
    profile for Karen Payne on Stack Exchange, a network of free, community-driven Q&A sites

    Wednesday, June 28, 2017 4:37 PM
    Moderator
  • Hi creepyspirals,

    Do you want to do this?

    I do this using one old way that you may refer to.

    Form1:

    Private Sub Form6_Load(sender As Object, e As EventArgs) Handles MyBase.Load
            Dim dt As New DataTable
            Dim strconnection As String = "Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=D:\C# and VB Support\Example(VB)\Sample\Data1.mdf;Integrated Security=True"
            Dim sql As String = "select * from test5 "
            Using con As New SqlConnection(strconnection)
                Try
                    con.Open()
                    Using cmd As New SqlCommand(sql, con)
                        Dim dataread As New SqlDataAdapter(cmd)
                        dataread.Fill(dt)
                        DataGridView1.DataSource = dt
                    End Using
                Catch ex As Exception
                End Try
            End Using
        End Sub
    
        Private Sub DataGridView1_CellDoubleClick(sender As Object, e As DataGridViewCellEventArgs) Handles DataGridView1.CellDoubleClick
            Dim number As String = DataGridView1.Rows(e.RowIndex).Cells("ColumnNumber").Value.ToString()
            Dim f As New Form7(number)
            f.Show()
        End Sub

    Form2:

      Private Number1 As String
        Public Sub New(number As String)
            Number1 = number
            InitializeComponent()
        End Sub
        Private Sub Form7_Load(sender As Object, e As EventArgs) Handles MyBase.Load
    
            Dim strconnection As String = "Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=D:\C# and VB Support\Example(VB)\Sample\Data1.mdf;Integrated Security=True"
            Dim sql As String = "select a.columnName, a.Columnsex,a.ColumnNumber,b.phone,b.address,b.information,b.blood,b.age from test5 as a left join test6 as b on a.columnnumber=b.columnnumber where a.columnNumber=@columnnumber  "
            Using con As New SqlConnection(strconnection)
                Try
                    con.Open()
                    Using cmd As New SqlCommand(sql, con)
                        cmd.Parameters.AddWithValue("@columnnumber", Number1)
                        Dim reader As SqlDataReader = cmd.ExecuteReader
                        While reader.Read
                            TextBox1.Text = reader(0).ToString()
                            TextBox2.Text = reader(2).ToString()
                            TextBox3.Text = reader(1).ToString()
                            TextBox4.Text = reader(3).ToString()
                            TextBox5.Text = reader(6).ToString()
                            TextBox6.Text = reader(7).ToString()
    
                            TextBox1.ReadOnly = True
                            TextBox2.ReadOnly = True
                            TextBox3.ReadOnly = True
                        End While
                    End Using
                Catch ex As Exception
    
                End Try
            End Using
        End Sub
    
        Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
    
            Dim strconnection As String = "Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=D:\C# and VB Support\Example(VB)\Sample\Data1.mdf;Integrated Security=True"
            Dim sql As String = "update Test6  set Phone='" + TextBox4.Text.ToString() + "', Blood='" + TextBox5.Text.ToString() + "', age='" + TextBox6.Text.ToString() + "' where ColumnNumber='" + Number1 + "'"
            Using con As New SqlConnection(strconnection)
                Try
                    con.Open()
                    Using cmd As New SqlCommand(sql, con)
                        cmd.ExecuteNonQuery()
                    End Using
                    con.Close()
                    MessageBox.Show("Update success!")
                Catch ex As Exception
                    MessageBox.Show(ex.Message)
                End Try
            End Using
        End Sub

    Best Regards,

    Cherry


    MSDN Community Support
    Please remember to click "Mark as Answer" the responses that resolved your issue, and to click "Unmark as Answer" if not. This can be beneficial to other community members reading this thread. If you have any compliments or complaints to MSDN Support, feel free to contact MSDNFSF@microsoft.com.

    Friday, June 30, 2017 4:16 AM
    Moderator
  • Hey, 

    Sorry for getting back to you so late. 

    I tired this method and it works. However when I close the form the edited elements are not saved into the database. I was wondering if there's anything else this code needs? like an insert into?

    thanks, 
    Cp

    Monday, July 10, 2017 11:21 PM