Clear the DataGridView without loosing the source - vb.net

I have a form with DataGridView, dataSourced by dataTable. When i insert the record at the end i press the Clear button or form all fields (textboxes, comboboxes, DGV checkboxes) get cleared automatically when i press the save button.
I normally clear the textboxes and comboboxes by writing:
textbox1.text = ""
combobox1.text = ""
but when i do clear DGV with this like:
dgvPurchase.dataSource = nothing
dgvPurchase.Refresh()
or
dgvPurchase.rows.clear()
It does clear the DGV but when i add new entry so DataGridView and data both do not appear into DGV. On the Form Load event I have the following code:
dtField = retrieveFull("ProductBasicInfo")
cmbPurProdID.DisplayMember = "ProdName"
cmbPurProdID.ValueMember = "ProdID"
cmbPurProdID.DataSource = dtField
dtPurchase.Columns.Add("ProdID")
dtPurchase.Columns.Add("ProdName")
dtPurchase.Columns.Add("RetailerID")
dtPurchase.Columns.Add("RetailerName")
dtPurchase.Columns.Add("UnitPrice")
dtPurchase.Columns.Add("Qty")
dtPurchase.Columns.Add("Amount")
dgvPurchase.DataSource = dtPurchase
Please guide me that is there any way that my DataSource do not disturb or if I clear it so it also refresh the DataSource.
This is the add button code, which adds the data into DataGridView
Try
For a As Integer = 0 To dtPurchase.Rows.Count - 1
If dtPurchase.Rows(a).Item("ProdID") = cmbPurProdID.SelectedValue Then
MessageBox.Show("This product is already enlisted")
Exit Sub
End If
Next
dRow = dtPurchase.NewRow
dRow.Item("ProdID") = cmbPurProdID.SelectedValue
dRow.Item("ProdName") = cmbPurProdID.Text
dRow.Item("RetailerID") = cmbPurRetailerID.SelectedValue
dRow.Item("RetailerName") = cmbPurRetailerID.Text
dRow.Item("UnitPrice") = txtPurUnitPrice.Text.Trim
dRow.Item("Qty") = txtPurQty.Text.Trim
dRow.Item("Amount") = txtPurAmount.Text.Trim
dtPurchase.Rows.Add(dRow)

You can create new empty DataTable and set it like this:
c#
DataTable emptyDT = new DataTable();
dgvPurchase.DataSource = emptyDT
vb.Net
Dim emptyDT As New DataTable()
dgvPurchase.DataSource = emptyDT
Does this work for you?

Related

Datagridview fills on second attempt. Never first attempt in Tab Control

I have a tab list where each tab has its own "x" amount of datagridviews. For some reason the first active tab fills the datagridviews just fine. When I click on the second tab in the Tab Control, the datagridviews fill the data but the gridview shows empty [When I followed the code it showed the records being filled into the datagridview].
If I click to another tab and then back to the second tab the gridview refills again and then shows the data. Does anyone know what may cause this? It is always the first attempt that never initially fills the other tabs [aside the first active tab]
So from what I can tell... nested Datagridviews can't be dynamically filled at first load using myDataGrid.Rows.Add(.....). The only way I was able to do this on first load was to build a Datatable and fill that instead. Can't understand why but it works....
With myDataGrid
Dim f As Font = .Font
.Columns.Clear()
.DataSource = Nothing
.DataMember = Nothing
.ColumnCount = 3
.AutoGenerateColumns = False
'.AutoSizeRowsMode = DataGridViewAutoSizeRowsMode.DisplayedCells
.Columns(0).Name = "MsgID"
.Columns(0).HeaderText = "MsgID"
.Columns(0).DataPropertyName = "MsgID"
.Columns(0).Visible = False
.Columns(1).Name = "Message"
.Columns(1).HeaderText = "Message"
.Columns(1).DataPropertyName = "Message"
.Columns(2).Name = "Sig"
.Columns(2).HeaderText = "Sig"
.Columns(2).DataPropertyName = "Sig"
.Columns(1).AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill
.Font = New Font(f, FontStyle.Bold)
.DefaultCellStyle.Alignment = 1
.Refresh()
End With
Dim dt As New DataTable
dt.Columns.Add("MsgID")
dt.Columns.Add("Message")
dt.Columns.Add("Sig")
dt.Columns(0).AutoIncrement = True
With ArrMessages(x)
Dim R As DataRow = dt.NewRow
R(0) = .MsgID
R(1) = .Msgs
R(2) = .Sig
dt.Rows.Add(R)
End With
'assign sourcing
myDataGrid.DataSource = dt
myDataGrid.Refresh()
Me.myDataGrid.Parent.Refresh()
myDataGrid.Refresh()

ListView combobox control at the end of line

Wondering how to place combobox control as last sub item for each row with some data coming from datasource. Have this code below:
LvSelMat.BeginUpdate()
Dim rodzajID as String = TreeMaterials.SelectedValue
Dim rodzajName as string = TreeMaterials.SelectedNode.Text
Dim parent as string = TreeMaterials.SelectedNode.Parent.Text
Dim li as ListViewItem
li = LvSelMat.Items.Add(parent)
li.SubItems.Add(rodzajName)
li.SubItems.Add(rodzajID)
'Here want to add combobox...
so far i tried like this but its only showing up combobox without any other items in row...
Dim combo as new combobox
combo.DataSource = New Variation().GetAll
combo.DisplayMember = "Name"
combo.ValueMember = "Id"
combo.dropdownstyle = ComboBoxStyle.DropDownList
' combo.height = item.bounds.height
' combo.location = new point(item.bounds.right, item.bounds.y)
LvSelMat.controls.add(combo)

How to get child datagrid values

How can I save values in child popup DataGridView?
I am having parent datagridview and child DataGridView in vb.net
Consider I have 2 columns and 2 rows.
When I click 1st column, I will get child DataGridView just near to this cell. Child DataGridView also has 2 rows and 2 columns where I can enter values.
When I click 2nd column, I'll get another new child DataGridView near this cell.
Now if I move back to first column, values I entered are lost. How can I save entered values in popup child window?
Here is my code:
sub cell_click Dim _pointCell As Point = Me.DgV.GetCellDisplayRectangle(e.ColumnIndex, e.RowIndex, True).Location Dim _pointGrid As Point = DgV.Location Dim _pointLocation As Point _pointLocation.X = _pointCell.X 'width _pointLocation.Y = _pointCell.Y 'height SelectionInGrid() mPopup.Show(DgV.PointToScreen(New Point(_pointLocation.X, _pointLocation.Y))) end sub
Public SelectionInGrid() Dim t1,t2 As New DataGridViewTextBoxColumn() Dim gv As New DataGridView
gv.Columns.Add(t1)
gv.Columns.Add(t2)
gv.Columns(0).HeaderText = "Employee"
gv.Columns(1).HeaderText = "Currency"
gv.Width = t1.Width + t2.Width
Dim mControlHost As ToolStripControlHost = New ToolStripControlHost(gv)
mControlHost.Padding = Padding.Empty
mControlHost.AutoSize = False
mPopup = New ToolStripDropDown()
mPopup.Padding = Padding.Empty
mPopup.Items.Add(mControlHost)
End
sub cell_click
Dim _pointCell As Point = Me.DgV.GetCellDisplayRectangle(e.ColumnIndex, e.RowIndex, True).Location
Dim _pointGrid As Point = DgV.Location
Dim _pointLocation As Point
_pointLocation.X = _pointCell.X 'width
_pointLocation.Y = _pointCell.Y 'height
SelectionInGrid()
mPopup.Show(DgV.PointToScreen(New Point(_pointLocation.X, _pointLocation.Y)))
end sub
Public SelectionInGrid()
Dim t1,t2 As New DataGridViewTextBoxColumn()
Dim gv As New DataGridView
gv.Columns.Add(t1)
gv.Columns.Add(t2)
gv.Columns(0).HeaderText = "Employee"
gv.Columns(1).HeaderText = "Currency"
gv.Width = t1.Width + t2.Width
Dim mControlHost As ToolStripControlHost = New ToolStripControlHost(gv)
mControlHost.Padding = Padding.Empty
mControlHost.AutoSize = False
mPopup = New ToolStripDropDown()
mPopup.Padding = Padding.Empty
mPopup.Items.Add(mControlHost)
End
The problem lies in the SelectionInGrid Sub which is called every single time you click a cell. In this function you have these lines:
Dim gv As New DataGridView
Dim mControlHost As ToolStripControlHost = New ToolStripControlHost(gv)
mPopup = New ToolStripDropDown()
This means that everytime cell_click runs a new DataGridView, a new ToolStripControlHost and a new ToolStripDropDown are created. To solve this you need to keep track of the different ToolStripDropDowns. For example using a dictionary:
Private PopUps As New Dictionary(Of String, ToolStripDropDown)
sub cell_click
Dim _pointCell As Point = Me.DgV.GetCellDisplayRectangle(e.ColumnIndex, e.RowIndex, True).Location
Dim _pointGrid As Point = DgV.Location
Dim _pointLocation As Point
_pointLocation.X = _pointCell.X 'width
_pointLocation.Y = _pointCell.Y 'height
If PopUps.ContainsKey(<Parent Selected cell identifyer>) Then
mPopup = PopUps(<Parent Selected cell identifyer>)
Else
SelectionInGrid()
PopUps.Add(<Parent Selected cell identifyer>,mPopup)
End If
mPopup.Show(DgV.PointToScreen(New Point(_pointLocation.X, _pointLocation.Y)))
end sub
I do believe this should work. "Parent Selected cell identifyer" must be something unique from the Parent DGV row/cell that was clicked.

populate textbox and picture box when row in listview selected

Hi i'm currently developing a system(vb.Net). here's the scenario, i a have textbox, picture box and a listview, where when i click a row from the listview it will populate the textbox and a picture box(e.g Users Details and her/his ID picture), but when i click the next row, only the textbox will change its value but the image on picturebox will not change.. here's my partially working code:
Try
If lvUsrProf.SelectedItems.Count > 0 Then
''Call userImage()
Dim adptr As New MySqlDataAdapter
Dim tbl As DataTable
Dim commbuild As MySqlCommandBuilder
'Dim uID As Integer
adptr.SelectCommand = cmd
tbl = New DataTable
adptr = New MySqlDataAdapter("SELECT pic_image FROM userprofile", uCon)
commbuild = New MySqlCommandBuilder(adptr)
adptr.Fill(tbl)
Dim lb() As Byte = tbl.Rows(0).Item("pic_image")
Dim lstr As New System.IO.MemoryStream(lb)
pboxID.Image = Image.FromStream(lstr)
lstr.Close()
txtIdNo.Text = lvUsrProf.SelectedItems(0).SubItems(0).Text
txtName.Text = lvUsrProf.SelectedItems(0).SubItems(1).Text
txtLstNam.Text = lvUsrProf.SelectedItems(0).SubItems(2).Text
cboDept.Text = lvUsrProf.SelectedItems(0).SubItems(3).Text
txtPOs.Text = lvUsrProf.SelectedItems(0).SubItems(4).Text
txtCont.Text = lvUsrProf.SelectedItems(0).SubItems(5).Text
txtEmail.Text = lvUsrProf.SelectedItems(0).SubItems(6).Text
'pboxID.SizeMode = PictureBoxSizeMode.CenterImage
End If
Catch ex As Exception
MsgBox(ex.Message)
Finally
uCon.Close()
End Try
Your brilliant ideas and suggestions will be much appreciated!.. Maraming Salamat!!
Looks like you are fetching all images from the table userprofile. Then for every selection you make you select the first item in that result. This image will always be the same since you aren't using a where clause in your select. Try adding something like this:
WHERE ID = lvUsrProf.SelectedItems(0).SubItems(0).Text
This should only fetch you one image and it should be the one connected to the selected account.

DataGridView not Refreshing/Updating/Reloading Data. After Child form closes

This is a VB.NET, Winforms App. I have a datagridview on "Form1" that uses a databinding.datasource which is an Entity Framework table. I fill the datagridview with the below function on Form1:
Sub PM_UnitViewGrid()
Try
_form1.UnitsBindingSource.DataSource = db.units.Where(Function(f) f.propertyId = _form1.CurrentPropertyId).OrderBy(Function(F) F.unitNumber)
_form1.UnitDataGridView.DataSource = _form1.UnitsBindingSource.DataSource
Dim iCount As Integer = _form1.UnitDataGridView.RowCount
For x As Integer = 0 To iCount - 1
If Not IsNothing(_form1.UnitDataGridView.Rows(x).Cells(4).Value) Then
Dim tid As Integer = _form1.UnitDataGridView.Rows(x).Cells(4).Value
Dim _ten As tenant = db.tenants.Single(Function(f) f.Occupantid = tid)
_form1.UnitDataGridView.Rows(x).Cells(1).Value = _ten.first_name + ", " + _ten.last_name
Else
Dim btnColumn As DataGridViewButtonCell = CType(_form1.UnitDataGridView.Rows(x).Cells(1), DataGridViewButtonCell)
btnColumn.Style.BackColor = Color.Green
_form1.UnitDataGridView.Rows(x).Cells(1).Value = "VACANT"
End If
Next
Catch ex As Exception
MessageBox.Show(ex.Message)
End Try
Return
End Sub
This works great and also assigns the needed values to an unbound column. The problem is that the cells(1) is a button. Which when clicked takes the user to another form as a new dialog window. The function for which is below. However, once the changes are made in that form I need for the datagridview to refresh the data that its using from the database and show the correct data. As it stands right now the values are not updating on the datagridview unless the app is completely exited and restarted. Nothing I have found seems to work and Refresh and Update only redraw the control. I need the underlying datasource to refresh and then the datagridview once the child form is exited.. This has had me stumped for a good 36 hours now and I am lost as to why nothing I am trying is working. ANY and all help would be greatly appreciated.
The sub that loads the child form based on the cells(1) button clicked is as follows:
Private Sub UnitDataGridView_CellContentClick(ByVal sender As System.Object, ByVal e As System.Windows.Forms.DataGridViewCellEventArgs) Handles UnitDataGridView.CellContentClick
UnitDataGridView.CommitEdit(DataGridViewDataErrorContexts.CurrentCellChange)
Dim y As DataGridViewCellEventArgs = e
Dim Tid As Integer = Nothing
If e.ColumnIndex = 1 Then
If Not e.RowIndex = -1 Then
If Not IsNothing(UnitDataGridView.Rows(e.RowIndex).Cells(4).Value) Then
currentTenent = UnitDataGridView.Rows(e.RowIndex).Cells(4).Value
TenentIdentification = currentTenent
If Not IsNothing(e) Then
If Not IsNothing(UnitDataGridView.Rows(e.RowIndex).Cells(4).Value) Then
Tid = UnitDataGridView.Rows(e.RowIndex).Cells(4).Value
Dim _ten As tenant = db.tenants.Single(Function(f) f.Occupantid = Tid) 'tenant is a table entity
TenantViewSubs.tenId = _ten.Occupantid
Dim t As New TenantView
t.tenId = tid
t.ShowDialog()
End If
End If
PropertyManagSubs.PM_UnitViewGrid() 'This is the function that is above that fills the datagridview
Else
Dim uTview As New UnassignedTenants
uTview.selectedProperty = selectedProperty 'selectedProperty is Integer
uTview.ShowDialog()
PropertyManagSubs.PM_UnitViewGrid() 'This is the function that is above that fills the datagridview
End If
End If
End If
End Sub
I tried each of the following code blocks after the t.ShowDialog() line with no change at all.
UnitDataGridView.Refresh()
.
UnitsBindingSource.Dispose()
UnitsBindingSource.DataSource = db.units.Where(Function(f) f.propertyId = selectedProperty).OrderBy(Function(f) f.unitNumber)
UnitDataGridView.DataSource = UnitsBindingSource.DataSource
.
UnitsBindingSource.DataSource = nothing
unitsBindingSource.DataSource = db.units.Where(Function(f) f.propertyId = selectedProperty).OrderBy(Function(f) f.unitNumber)
UnitDataGridView.DataSource = UnitsBindingSource.DataSource
I finally fixed this on my own.. It was in the way I passed my db context to the databinding..
I simply wrote the below sub:
Private Sub UpdateValues()
Dim context As New storageEntities 'storageEntities is an Entity
Dim query = context.units.Where(Function(F) F.propertyId = selectedProperty).OrderBy(Function(f) f.unitNumber)
UnitDataGridView.DataSource = query
End Sub
Then anytime a child form updated data I simply call
UpdateValues()
After the dialog box closes.
This may help someone else with the same problems so that is why I am posting it.