简体   繁体   中英

Problem in Data display from database using datagridview in vb.net

Im using vb.net windows forms, VS 2019, .net framework 4.7.2 and mysql.

I tried datagridview in a form to display data from my database and its working perfectly fine.

But,

when i tried to use the same procedure, displaying data from the same database using datagridview in a child form (which i call via parent form that docks the child form over a region in parent form), it is not displaying any data, while the query works perfectly fine, its updating the data in database, but the data isn't displaying in this parent-child case.

Tho, the same code works perfectly fine and displays data if its used in a separate form.

I don't know what is the problem actually.

I had to attach more than one picture to explain clearly so i uploaded them and the link is given as:

https://imgur.com/a/6xka1B4

But, i have merged all the snips of the code from different forms as well:

1 The sub-class Custom_LoadDataGrid is called here and working correctly and displaying data in the gridview

 DB.Custom_LoadDataGrid("SELECT item_name as 'NAME', item_price as 'PRICE', quantity as 'QUANTITY', Amount as 'AMOUNT' FROM transaction WHERE client_name ='" + Label11.Text.ToString + "'")
 DB.myConnection.Close()

2 The sub Custom_LoadDataGrid which was called above

Public Sub Custom_LoadDataGrid(ByVal search As String)

    Try
        connString = "server=127.0.0.1;Port=3306;Database=smartcart;Uid=root;Pwd="

        myConnection.ConnectionString = connString
        myConnection.Open()

        sql = search.ToString

        DataAdapter = New MySqlDataAdapter(sql, myConnection)
        Datacmd = New MySqlCommand(sql, myConnection)
        DataAdapter.Fill(DataSet, DbName)
        MaxRows = DataSet.Tables(DbName).Rows.Count

        Dim dt1 As New DataTable
        DataSet.Tables.Add(dt1)
        DataAdapter.Fill(dt1)
        Portal.Guna2DataGridView1.DataSource = dt1.DefaultView
        ReleaseDb()

    Catch ex As Exception
        MsgBox("Something went wrong")
    End Try

End Sub

3 i made this sub-class to call child forms and dock in the region somewhere in the parent forms

Private Sub OpenChildForm(childForm As Form)

    'Open only form'
    If currentChildForm IsNot Nothing Then
        currentChildForm.Close()
    End If
    currentChildForm = childForm
    'end'
    childForm.TopLevel = False
    childForm.FormBorderStyle = FormBorderStyle.None
    childForm.Dock = DockStyle.Fill
    Controls_panel.Controls.Add(childForm)
    Controls_panel.Tag = childForm
    childForm.BringToFront()
    childForm.Show()

End Sub

4 here the child form is called

Private Sub Stock_manag_button_Click(sender As Object, e As EventArgs) Handles Stock_manag_button.Click

    Sub_menu_panel.Hide()
    ActivateButton(sender)
    OpenChildForm(New Stock_management)

End Sub

5 This sub-class Custom_Load_DataGrid is called here but is not displaying data in gridview

    DB.Custom_Load_DataGrid("SELECT * FROM addition_stock ")
    DB.myConnection.Close()

'6 the sub-class Custom_Load_DataGrid is exactly same as Custom_LoadDataGrid (but obviously with different variables and relavent form name) but this is not displaying data in gridview just in this this case of parent-child forms tho this one works fine too when used for seperate forms.

Public Sub Custom_Load_DataGrid(ByVal search As String)

    Try
        connString = "server=127.0.0.1;Port=3306;Database=smartcart;Uid=root;Pwd="

        myConnection.ConnectionString = connString
        myConnection.Open()

        sql = search.ToString

        DataAdapter = New MySqlDataAdapter(sql, myConnection)
        Datacmd = New MySqlCommand(sql, myConnection)
        DataAdapter.Fill(DataSet, DbName)
        MaxRows = DataSet.Tables(DbName).Rows.Count
        MsgBox(MaxRows.ToString)
        Dim dt2 As New DataTable
        DataSet.Tables.Add(dt2)
        DataAdapter.Fill(dt2)
        Stock_addition.Guna2DataGridView1.DataSource = dt2.DefaultView
        ReleaseDb()

    Catch ex As Exception
        MsgBox("Something went wrong")
    End Try

End Sub

Can I get you to do this, in a new project, as a mini tutorial to make your life easier:

  • make a new project
  • Add a Form
  • Add a DataSet
  • Open the DataSet, right click in the surface and add a tableadapter
  • create a connection string to store in the settings: Pick mysql connector (note for this to work you need mysql connector AND ALSO mysql for visual studio https://dev.mysql.com/downloads/windows/visualstudio/ ) and fill in the details to create a database connection string make sure the test connection succeeds
  • proceed through the wizard choosing "query that returns rows", "by sql", enter a query of SELECT * FROM addition_stock WHERE ID = @id
  • write names of FillByID, and GetDataByID
  • finish

You'll see something that looks like a database table appear, with a thing called addition_stockTableAdapter underneath it

  • Right click the tableadapter, choose add.. query
  • add another query that is more relevant to how you will search this table, like maybe SELECT * FROM addition_stock WHERE stock_code = @stockCode
  • call it FillByStockCode/GetDataByStockCode
  • always give relevant names to your fill/get data methods

Always make the first query that creates the datatable/tableadapter pair a "select where id =" - it makes things easier later on. Add as many additional queries as you will need

Do the same thing again (Add a tableadapter) this time with a table that is either a parent or a child of addition_stock - it doesn't matter which, I'm just trying to demonstrate something here. Make sure you use a table that has a foreign key in the database, to addition_stock

Once you add your other datatable/tableadapter pair that is related to addition_stock you will see a line connecting the two datatables

  • Right click this line and choose "show relation labels" to display the name of the relation - it comes from the foreign key in the database

Now we are going to add a convenience method to load child data based on the parent id

  • Right click your child tableadapter and choose Add Query
  • add a query of SELECT * FROM tablenamehere WHERE parentidcolumnnamehere = @parentid and call it a suitable FillByXxx - obviously Replace the table name, column name and xxx with real values

  • save your DataSet and switch to the forms designer

  • show the Data Sources window (view menu.. other windows)
  • expand all the nodes of your DataSet - you'll see a parent table and two child tables, one underneath the parent, one not
  • drag the parent table out of datasources and onto the form - a datagridview with columns will appear, as will a tableadapter, bindingnavigator, DataSet and a bindingsource in the tray at the bottom. The nav has a textbox you can write an id into and a button to press. The datagridview columns are set up appropriately and the grid is bound to the bindingsource. The bindingsource is bound to the DataSet parent table.
  • run the app, enter an ID in the textbox, click fill, edit the name of something, click save, go use mysql workbench to look in the db. Super; you can download, edit and save db data and you haven't written a single line of code; you're just using the thousands of lines of code visual studio has written for you.
  • stop the app, go back to the forms designer
  • drag the child table that is underneath the parent table onto the form. More items appear - a datagridview bound to another bindingsource, another navigator etc. You can delete this second navigator- we won't use it
  • take a look at the bindingsource of the child table - note that it is NOT bound directly to the DataSet but instead it is bound to the other bindingsource, with a DataMember property that is set to the name of the relation line between the two tables
  • switch to code view and look at the code of the Fill toolstripmenu that fills the parent record by the id/whatever. If there is any redundant code from the child bindingnavigator, remove it (or comment it out: it could be slightly useful for the next step
  • under the line of code that fills the parent datatable by id put the following code:

    childTableAdapter.ClearBeforeFill = False yourDatasetName.ChildTableName.Clear() For Each parentRow in yourDataSetName.YourParentTableName childTableAdapter.FillByParentId(yourDataSetName.ChildTableName, parentRow.Id) Next

Run the app again, enter the parent id, click fill. The parent data and the related child data loads. Great, but the real magic happens when we load multiple parent rows. Go back to code and swap the FillById on the parent tableadapter for the other query you write (if you didn't do one, go back to DataSet, Add a query to the parent table adapter that loads multiple rows, like select * from person where lastname = @lastname so we can enter a last name like smith, of which there are many) so now your code looks like this in the fill:

parentTableAdapter.FillBySonethingThatGetsMultipleRows(yourDataSetName.ParentTableName, fillByTextboxName.Text)

childTableAdapter.ClearBeforeFill = False
yourDatasetName.ChildTableName.Clear()
For Each parentRow in yourDataSetName.YourParentTableName
  childTableAdapter.FillByParentId(yourDataSetName.ChildTableName, parentRow.Id)
Next

You'll note that you get multiple parent rows, you load multiple sets of child rows in the loop, but when you run the app and you choose a different parent in the parent grid the child grid automatically filters to show only the children of the currently selected parent

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM