VB.NET DataSet table data empty - vb.net

I'm trying to use the dataset for a report, but the data is gone when I try to use it. Here is my code for the most part:
Variables:
Dim ResultsDataView As DataView
Dim ResultsDataSet As New DataSet
Dim ResultsTable As New DataTable
Dim SQLQuery As String
Search:
This is where a datagrid is populated in the main view. The data shows up perfectly.
Private Sub Search(Optional ByVal Bind As Boolean = True, Optional ByVal SearchType As String = "", Optional ByVal SearchButton As String = "")
Dim SQLQuery As String
Dim ResultsDataSet
Dim LabelText As String
Dim MultiBudgetCenter As Integer = 0
SQLQuery = "A long and detailed SQL query that grabs N rows with 7 columns"
ResultsDataSet = RunQuery(SQLQuery)
ResultsTable = ResultsDataSet.Tables(0)
For Each row As DataRow In ResultsTable.Rows
For Each item In row.ItemArray
sb.Append(item.ToString + ","c)
Response.Write(item.ToString + "\n")
Response.Write(vbNewLine)
Next
sb.Append(vbCr & vbLf)
Next
'Response.End()
If Bind Then
BindData(ResultsDataSet)
End If
End Sub
Binding Data:
I think this is a cause in the issue.
Private Sub BindData(ByVal InputDataSet As DataSet)
ResultsDataView = InputDataSet.Tables("Results").DefaultView
ResultsDataView.Sort = ViewState("SortExpression").ToString()
ResultsGridView.DataSource = ResultsDataView
ResultsGridView.DataBind()
End Sub
Reporting action:
This is where I am trying to use the table data. But it is showing as nothing.
Protected Sub ReportButton_Click(sender As Object, e As EventArgs) Handles ReportButton.Click
For Each row As DataRow In ResultsTable.Rows
For Each item In row.ItemArray
Response.Write(item.ToString)
Next
Next
End Sub
The reason I'm trying to loop through this data is to both display the data in a gridview on the main view as well as export the data to CSV. If there is a different way to export a SQL query to CSV, I'm open to any suggestions.
There has to be something I can do to get the data from the SQL query to persist through the ReportButton_Click method. I've tried copying the datatable, I've tried global variables, I've tried different methods of looping through the dataset. What am I missing?!
Thank you all in advance.
EDIT
Here is the Page_Load:
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
If Page.IsPostBack Then
'set focus to postback control
Dim x As String = GetPostBackControlName(Page)
If Len(x) > 0 Then
x = x.Replace("$", "_")
SetFocus(x)
End If
End If
If Not IsPostBack Then
ResultsGridView.AllowPaging = False
'Enable Gridview sorting
ResultsGridView.AllowSorting = True
'Initialize the sorting expression
ViewState("SortExpression") = "ID DESC"
'Populate the Gridview
Search()
End If
End Sub

In your search function add this line after the ResultsTable setting
ResultsTable = ResultsDataSet.Tables(0)
Session("LastSearch") = ResultsTable
Then in your report click event handler recover your data from the Session variable
Protected Sub ReportButton_Click(sender As Object, e As EventArgs) Handles ReportButton.Click
ResultsTable = DirectCast(Session("LastSearch"), DataTable)
For Each row As DataRow In ResultsTable.Rows
For Each item In row.ItemArray
Response.Write(item.ToString)
Next
Next
End Sub
You need to read about ASP.NET Life Cycle and understand that every time ASP.NET calls your methods it creates a new instance of your Page class. Of course this means that global page variables in ASP.NET are not very useful.
Also consider to read about that Session object and not misuse it.
What is the difference between SessionState and ViewState?

Related

VB - Gridview style after index changed

i've a gridview with pagesize=10, when i load the page and bind grid i've the correct style applied (checkbox cheched or no), but when i go to second page i can't apply the style (checkbox always not checked) and if i came back to the first page i haven't the correst style applied.
At the page load i store all checkbox states into a dictonary to check when i bind the grid.
Public listaCheckbox As New Dictionary(Of Integer, Boolean)
I tried to apply a style to the first row to understand where I'm wrong but it's always the same thing.
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
RecuperaCheckbox() 'to store all checkbox value into listaCheckbox, it works
If IsPostBack = False Then
Me.BindGrid2()
End If
End Sub
Protected Sub OnPageIndexChanging(sender As Object, e As GridViewPageEventArgs) Handles GridViewListaEsp.PageIndexChanging
GridViewListaEsp.PageIndex = e.NewPageIndex
Me.BindGrid2()
End Sub
Private Sub BindGrid2()
Query = "SELECT ...
FROM ...;"
List.SelectCommand = Query
GridViewListaEsp.DataBind()
For i = 0 To GridViewListaEsp.Rows.Count - 1
Dim chk As CheckBox = GridViewListaEsp.Rows(i).FindControl("chkOnOff")
Dim id_azienda As String = GridViewListaEsp.Rows(i).Cells(1).Text
listaCheckbox.TryGetValue(id_azienda, chk.Checked) 'works only at the first page load
Next
GridViewListaEsp.Rows(0).Attributes.Add("style", "background-color:aqua") 'works only at the first page load
End Sub
I found the solution:
to bind grid i used the command:
list.SelectCommand = Query
this was working for all thing except for the application of the style after index changing.
I changed part of code with this:
cmdExist = New SACommand(szPrintf(Query), con)
drExist = cmdExist.ExecuteReader
Dim DT As New DataTable
DT.Load(drExist)
GridViewListaEsp.DataSource = DT
GridViewListaEsp.DataBind()
And now i can apply new style after change index page!

VB.Net populating text boxes from text file

I'm creating an inventory management system where the data is stored in a text file. I'm able to save data to the text file, however on the tracker screen it should show current inventory such as: Manufacturer, Processor, Video, Form, RAM, etc. However, all my text boxes remain blank and I'm not sure why. It's not reading properly or updating the text.
frmTracker.vb
Private Sub txtManufacturer_TextChanged(sender As Object, e As EventArgs) Handles txtManufacturer.TextChanged
Dim objMyStreamReader = System.IO.File.OpenText("inventory.txt")
Dim strInventory = objMyStreamReader.ReadLine()
objMyStreamReader.Close()
txtManufacturer.AppendText(strInventory)
End Sub
This is how I'm currently saving the data to the text file.
frmItemEntry.vb
Private Sub btnSave_Click(sender As Object, e As EventArgs) Handles btnSave.Click
Dim objMyStreamReader As System.IO.StreamReader
Dim objMyStreamWriter As System.IO.StreamWriter = System.IO.File.CreateText("inventory.txt")
Dim strInventory As String
objMyStreamWriter.WriteLine(txtManufacturerEntry.Text)
objMyStreamWriter.WriteLine(txtProcessorEntry.Text)
objMyStreamWriter.WriteLine(txtVideoEntry.Text)
objMyStreamWriter.WriteLine(txtFormEntry.Text)
objMyStreamWriter.WriteLine(txtRamEntry.Text)
objMyStreamWriter.WriteLine(txtVramEntry.Text)
objMyStreamWriter.WriteLine(txtHdEntry.Text)
objMyStreamWriter.WriteLine(chkWirelessEntry.CheckState)
objMyStreamWriter.Close()
Me.Close()
End Sub
Example from inventory.txt
Dell
i5
Nvidia
Desktop
8
4
600
0
To be honest, controls should never be used as the primary store for your data in a program. You should really be creating a class and a list of that class to store your data.
You can then read your data into the list from your file, and then, display it from there in your form.
There are several ways of navigating through the data and saving updates. The suggestion below uses buttons for next item and previous item, and a button to save update the file.
It's all pretty self explanatory, but if there's something your not sure about, please have a google and learn something new :-D
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
ReadDataFile()
DisplayItem(0)
End Sub
Private Class InventoryItem
Public Property Manufacturer As String
Public Property Processor As String
Public Property Video As String
Public Property FormFactor As String
Public Property Ram As String
Public Property VRam As String
Public Property Hd As String
Public Property Wireless As CheckState
Public Sub New()
Manufacturer = ""
Processor = ""
Video = ""
FormFactor = ""
Ram = ""
VRam = ""
Hd = ""
Wireless = CheckState.Unchecked
End Sub
End Class
Dim Inventory As New List(Of InventoryItem)
Dim currentItemIndex As Integer
Private Sub ReadDataFile()
Using objMyStreamReader As New StreamReader("k:\inventory.txt")
Do Until objMyStreamReader.EndOfStream
Dim newItem As New InventoryItem
newItem.Manufacturer = objMyStreamReader.ReadLine()
newItem.Processor = objMyStreamReader.ReadLine()
newItem.Video = objMyStreamReader.ReadLine()
newItem.FormFactor = objMyStreamReader.ReadLine()
newItem.Ram = objMyStreamReader.ReadLine()
newItem.VRam = objMyStreamReader.ReadLine()
newItem.Hd = objMyStreamReader.ReadLine()
Dim wirelessValue As String = objMyStreamReader.ReadLine()
If wirelessValue = "0" Then
newItem.Wireless = CheckState.Unchecked
ElseIf wirelessValue = "1" Then
newItem.Wireless = CheckState.Checked
End If
Inventory.Add(newItem)
Loop
End Using
End Sub
Private Sub SaveDataFile()
Using objMyStreamWriter As New System.IO.StreamWriter("k:\inventory.txt", False)
For Each item As InventoryItem In Inventory
objMyStreamWriter.WriteLine(item.Manufacturer)
objMyStreamWriter.WriteLine(item.Processor)
objMyStreamWriter.WriteLine(item.Video)
objMyStreamWriter.WriteLine(item.FormFactor)
objMyStreamWriter.WriteLine(item.Ram)
objMyStreamWriter.WriteLine(item.VRam)
objMyStreamWriter.WriteLine(item.Hd)
If item.Wireless = CheckState.Checked Then
objMyStreamWriter.WriteLine("1")
Else
objMyStreamWriter.WriteLine(0)
End If
Next
End Using
End Sub
Private Sub DisplayItem(index As Integer)
With Inventory(index)
txtManufacturerEntry.Text = .Manufacturer
txtProcessorEntry.Text = .Processor
txtVideoEntry.Text = .Video
txtFormEntry.Text = .FormFactor
txtRamEntry.Text = .Ram
txtVramEntry.Text = .VRam
txtHdEntry.Text = .Hd
chkWirelessEntry.CheckState = .Wireless
End With
End Sub
Private Sub BtnUpdateItem_Click(sender As Object, e As EventArgs) Handles BtnUpdateItem.Click
With Inventory(currentItemIndex)
.Manufacturer = txtManufacturerEntry.Text
.Processor = txtProcessorEntry.Text
.Video = txtVideoEntry.Text
.FormFactor = txtFormEntry.Text
.Ram = txtRamEntry.Text
.VRam = txtVramEntry.Text
.Hd = txtHdEntry.Text
.Wireless = chkWirelessEntry.CheckState
End With
SaveDataFile()
End Sub
Private Sub BtnPreviousItem_Click(sender As Object, e As EventArgs) Handles BtnPreviousItem.Click
If currentItemIndex > 0 Then
currentItemIndex -= 1
DisplayItem(currentItemIndex)
End If
End Sub
Private Sub BtnNextItem_Click(sender As Object, e As EventArgs) Handles BtnNextItem.Click
If currentItemIndex < Inventory.Count - 1 Then
currentItemIndex -= 1
DisplayItem(currentItemIndex)
End If
End Sub
First change the format of your text file.
Dell,i5,Nvidia,Desktop,8,2,600,True
Acer,i7,Intel,Desktop,16,4,1GB,True
HP,Pentium,Diamond Viper,Desktop,4,2,200,False
Surface Pro,i7,Intel,Laptop,8,2,500,True
Each line is a record and each field in the record is separated by a comma (no spaces so we don't have to .Trim in code) (a space within a field is fine, notice Surface Pro).
Now it is easier to read the file in code.
This solution uses a BindingSource and DataBindings. This simplifies Navigation and editing and saving the data.
Public Class Form5
Private bs As BindingSource
Private dt As New DataTable
#Region "Set Up the Form"
Private Sub Form5_Load(sender As Object, e As EventArgs) Handles MyBase.Load
AddColumnsToDataTable()
FillDataTable()
AddDataBindings()
End Sub
Private Sub AddColumnsToDataTable()
'Prepare the DataTable to hold data
dt.Columns.Add("Manufacturer", GetType(String))
dt.Columns.Add("Processor", GetType(String))
dt.Columns.Add("Video", GetType(String))
dt.Columns.Add("Form", GetType(String))
dt.Columns.Add("RAM", GetType(String))
dt.Columns.Add("VRAM", GetType(String))
dt.Columns.Add("HD", GetType(String))
dt.Columns.Add("Wireless", GetType(Boolean))
End Sub
Private Sub FillDataTable()
'ReadAllLines returns an array of the lines in a text file
'inventory.txt is stored in the bin\Debug folder of your project
'This is the current directory so it does not require a full path.
Dim lines = File.ReadAllLines("inventory.txt")
'Now it is easy to split each line into fields by using the comma
For Each line As String In lines
'Split returns an array of strings with the value of each field
Dim items = line.Split(","c)
'Each item in the array can be added as a field to the DataTable row
dt.Rows.Add(items(0), items(1), items(2), items(3), items(4), items(5), items(6), CBool(items(7)))
'Notice that the last element is changed from a string to a boolean. This is
'the Wireless field which is bound to the check box. The string "True" or "False" is
'changed to a Boolean so it can be used as the .Checked property (see bindings)
Next
End Sub
Private Sub AddDataBindings()
'Create a new instance of the BindingSource class
bs = New BindingSource()
'Set the DataSource to the DataTable we just filled
bs.DataSource = dt
'Now you can set the bindings of each control
'The .Add method takes (Name of Property to Bind, the BindingSource to use, The Field name
'from the DataTable.
txtForm.DataBindings.Add("Text", bs, "Form")
txtHd.DataBindings.Add("Text", bs, "HD")
txtManufacturer.DataBindings.Add("Text", bs, "Manufacturer")
txtProcessor.DataBindings.Add("Text", bs, "Processor")
txtRam.DataBindings.Add("Text", bs, "RAM")
txtVideo.DataBindings.Add("Text", bs, "Video")
txtVram.DataBindings.Add("Text", bs, "VRAM")
'Notice on the CheckBox we are using the Checked property.
chkWireless.DataBindings.Add("Checked", bs, "Wireless")
End Sub
#End Region
Private Sub btnAdd_Click(sender As Object, e As EventArgs) Handles btnAdd.Click
'Add a blank row to the DataTable
'A Boolean is like a number, a String can be Nothing but a Boolean must
'have a value so we pass in False.
dt.Rows.Add(Nothing, Nothing, Nothing, Nothing, Nothing, Nothing, Nothing, False)
'Find the position of the last row
Dim i As Integer = bs.Count - 1
'Move to the new empty row
bs.Position = i
End Sub
#Region "Navigation Code"
Private Sub btnPrevious_Click(sender As Object, e As EventArgs) Handles btnPrevious.Click
'The binding source Position determins where in the data you are
'It starts at zero
If bs.Position = 0 Then
MessageBox.Show("This is the first item.")
Return 'This exits the sub, you can use Exit Sub in vb
'but Return is common in other languages so it is good to learn
Else
'As the position of the BindingSource changes the boud TextBoxes
'change their data.
bs.Position = bs.Position - 1
End If
End Sub
Private Sub btnNext_Click(sender As Object, e As EventArgs) Handles btnNext.Click
' If you are not at the end of the list, move to the next item
' in the BindingSource.
If bs.Position + 1 < bs.Count Then
bs.MoveNext()
' Otherwise, move back to the first item.
Else
bs.MoveFirst()
End If
End Sub
#End Region
#Region "Save the Data"
Private Sub SaveDataTable()
'Resave the whole file if this was a real app you would use a database
Dim sb As New StringBuilder
'A string builder keeps the code from creating lots of new strings
'Strings are immutable (can't be changed) so every time you think you are
'changing a string, you are actually creating a new one.
'The string builder is mutable (changable)
For Each row As DataRow In dt.Rows
'The ItemsArray returns an array of objects containing all the
'values in each column of the data table.
Dim rowValues = row.ItemArray
'This is a bit of Linq magic that turns the values (objects) into strings
'Underneath it is performing a For loop on each object in the array
Dim strRowValues = From o In rowValues
Select Convert.ToString(o)
'Now that we have strings we can use the String.Join with the comma
'to get the format of the text file
sb.AppendLine(String.Join(",", strRowValues))
Next
'Finally we change the StringBuilder to a real String
'The inventory.txt is stored in the bin\Debug directory so it is current directory
'no additional path required
File.WriteAllText("inventory.txt", sb.ToString)
End Sub
Private Sub Form5_FormClosing(sender As Object, e As FormClosingEventArgs) Handles MyBase.FormClosing
'Because our binding is two-way any additions or changes to the text
'in the text boxes or check box are reflected in the DataTable.
SaveDataTable()
End Sub
#End Region
End Class
Once you remove the comments, there is really very little code here. The #Region...#End Region tags make it easy to collapse code sections you are not working on and find areas quickly.

Form Loads slowly in vb.net

I am currently working in ERP project on vb.net. I want to load product data in a textbox on form load. I am using autocomplete method but having a data of around 26000 the form loads slowly for 4 mins. Is there any way to avoid this or is there any way to call this function in background when the application starts?
This is my autocomplete textbox code. It works fine but it hangs alot as of the data is so large.
Private Sub pn()
Try
con = Class1.dbconn
Dim dt As New DataTable
Dim ds As New DataSet
ds.Tables.Add(dt)
Dim da As New SqlDataAdapter("select [Part Name] from
Part_Master_Download$", con)
da.Fill(dt)
Dim r As DataRow
TextBox9.AutoCompleteCustomSource.Clear()
For Each r In dt.Rows
TextBox9.AutoCompleteCustomSource.Add(r.Item(0).ToString)
Next
con.Close()
Catch ex As Exception
MessageBox.Show(ex.Message)
End Try
End Sub
the properties of the textbox should be set to true for autocompletetextbox
Don't populate the AutoCompleteCustomSource in a loop. Populate an array first and then load the list in one go with a single call to AddRange:
Dim items = dt.Rows.Cast(Of DataRow)().
Select(Function(row) CStr(row(0)).
ToArray()
TextBox9.AutoCompleteCustomSource.AddRange(items)
You should find that that speeds things up considerably. If there's still a problem with performance, we can look a bit further.
EDIT: To prove my point, I just tested the following code:
Public Class Form1
Private timer As Stopwatch
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
timer = Stopwatch.StartNew()
Dim rng As New Random
Dim a = Convert.ToInt32("a"c)
Dim z = Convert.ToInt32("z"c)
Dim items = Enumerable.Range(1, 26000).Select(Function(n) Convert.ToChar(rng.Next(a, z + 1)).ToString())
For Each item In items
TextBox1.AutoCompleteCustomSource.Add(item)
Next
End Sub
Private Sub Form1_Shown(sender As Object, e As EventArgs) Handles Me.Shown
MessageBox.Show(timer.Elapsed.ToString())
End Sub
End Class
and the message displayed "00:03:08.3167858", i.e. just over three minutes to load the list. I then changed the Load event handler to this:
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
timer = Stopwatch.StartNew()
Dim rng As New Random
Dim a = Convert.ToInt32("a"c)
Dim z = Convert.ToInt32("z"c)
Dim items = Enumerable.Range(1, 26000).Select(Function(n) Convert.ToChar(rng.Next(a, z + 1)).ToString())
TextBox1.AutoCompleteCustomSource.AddRange(items.ToArray())
End Sub
so a single call to AddRange instead of calling Add in a loop, and the message was "00:00:00.0557427", i.e. just under 56 milliseconds. Is that better?
You can use paging to control the amount of returned data. Check this link for detailed examples.
Another way is to use (Task Async and await) so you won't lock your UI.
Here is a few last suggestions not related directly to the question but might help clean the code a bit:
you can skip the dataset and use the datatable directly, you don't need it for just one table.
Bind your results in the datatable to a datagridview or a combobox instead of iterating through your results and filling a textbox.
cheers

How do I add a new row to a binding source

I am trying to programmatically add a new row to a binding source . I know calling the bsSource.AddNew() adds a new row which I cast as a DataRowView and I set my values. My problem is this - the DataRowView.Row shows a RowState of detached. I do not want it to be detached ; I believe it should show added - I also do NOT want it to commit the change to the database (There is a very valid reason for this). I want to pick the time for that later.
My code is as follows:
private Sub AddToRelationSource(binID As Integer, gradeID As Integer, IsChecked As Boolean)
Dim drv As DataRowView = DirectCast(bsBinGrades.AddNew(), DataRowView)
drv.Row("IsSelected") = IsChecked
drv.Row("BinID") = binID
drv.Row("GradeID") = gradeID
' I tried drv.EmdEdit(0 drv.Row.EndEdit() - Row State still shows detached
End Sub
The BindingSource AddNew method does not actually add a new record to the underlying datasource , it simply adds it to the bindingsource as a detached item. When using the datatabel as a datasource I needed to get the datatable and use the AddRow() method - this properly set the value in my bindingsource to added so that when the changes would be committed to the database on bindingsource.Update() method.
The code I used:
Dim drv As DataRowView = DirectCast(bsData.AddNew(), DataRowView)
drv.BeginEdit()
drv.Row.BeginEdit()
drv.Row("IsSelected") = IsChecked
drv.Row.EndEdit()
drv.DataView.Table.Rows.Add(drv.Row)
The last line is what actually added the item to the datasource - I misunderstood BindingSource.AddNew() .
The following may be in the right direction. First I used a few language extension methods e.g.
Public Module BindingSourceExtensions
<Runtime.CompilerServices.Extension()>
Public Function DataTable(ByVal sender As BindingSource) As DataTable
Return CType(sender.DataSource, DataTable)
End Function
<Runtime.CompilerServices.Extension()>
Public Sub AddCustomer(ByVal sender As BindingSource, ByVal FirstName As String, ByVal LastName As String)
sender.DataTable.Rows.Add(New Object() {Nothing, FirstName, LastName})
End Sub
<Runtime.CompilerServices.Extension()>
Public Function DetachedTable(ByVal sender As BindingSource) As DataTable
Return CType(sender.DataSource, DataTable).GetChanges(DataRowState.Detached)
End Function
<Runtime.CompilerServices.Extension()>
Public Function AddedTable(ByVal sender As BindingSource) As DataTable
Return CType(sender.DataSource, DataTable).GetChanges(DataRowState.Added)
End Function
End Module
Now load ID, FirstName and LastName into a DataTable, Datatable becomes the DataSource of a BindingSource which is the BindingSource for a BindingNavigator and are wired up to a DataGridView.
Keeping things simple I mocked up data, has no assertions e.g. make sure we have valid first and last name, instead concentrate on the methods.
First use a extension method to add a row to the underlying DataTable of the BindingSource.
bsCustomers.AddCustomer("Karen", "Payne")
Now check to see if there are detached or added rows
Dim detachedTable As DataTable = bsCustomers.DetachedTable
If detachedTable IsNot Nothing Then
Console.WriteLine("Has detached")
Else
Console.WriteLine("No detached")
End If
Dim AddedTable As DataTable = bsCustomers.AddedTable
If AddedTable IsNot Nothing Then
Console.WriteLine("Has added")
Else
Console.WriteLine("None added")
End If
Since we are not talking to the database table, the primary key is not updated as expected and since you don't want to update the database table this is fine. Of course there is a method to get the primary key for newly added records if you desire later in your project.
Addition
Private Sub BindingSource1_AddingNew(ByVal sender As System.Object, ByVal e As System.ComponentModel.AddingNewEventArgs) Handles BindingSource1.AddingNew
Dim drv As DataRowView = DirectCast(BindingSource1.List, DataView).AddNew()
drv.Row.Item(0) = "some value"
e.NewObject = drv
' move to new record
'BindingSource1.MoveLast()
End Sub
'This routine takes the AddForm with the various fields that the user
'fills in and calls the TableAdapter's Insert method.
'After that is done, then the table has be be reflected back to the
'various components.
Private Sub AddRecord()
'The following line did not work because I could not get
'the bs definition down.
'Tried the BindingSource but in gave an error on
'DataRowView so I came up with an alternate way of
'adding the row.
'Dim drv As DataRowView = DirectCast(bsData.AddNew(), DataRowView)
'Dim drv As DataRowView = DirectCast(RecTableBindingSource.AddNew(), DataRowView)
'drv.BeginEdit()
'drv.Row.BeginEdit()
'drv.Row("Title") = "Order, The"
'drv.Row.EndEdit()
'drv.DataView.Table.Rows.Add(drv.Row)
RecTableTableAdapter.Insert(pAddForm.tTitle.Text,
pAddForm.tCast.Text,
pAddForm.tAKA.Text,
pAddForm.tRelated.Text,
pAddForm.tGenre.Text,
pAddForm.tRated.Text,
pAddForm.tRelease.Text,
pAddForm.tLength.Text)
Validate()
RecTableBindingSource.EndEdit()
RecTableTableAdapter.Update(VideoDBDataSet.RecTable)
RecTableAdapterManager.UpdateAll(VideoDBDataSet)
RecTableTableAdapter.Fill(VideoDBDataSet.RecTable)
VideoDBDataSet.AcceptChanges()
End Sub
'Here is my Delete Record routine
Private Sub DeleteRecordToolStripMenuItem_Click(sender As Object, e As EventArgs) Handles DeleteRecordToolStripMenuItem.Click
Dim RowIndex As Int32
If (dgvRec.SelectedRows.Count > 0) Then
RowIndex = dgvRec.SelectedRows(0).Index
'Now we have to delete the record
dgvRec.Rows.RemoveAt(RowIndex)
dgvRec.CommitEdit(RowIndex)
dgvRec.EndEdit()
Validate()
RecTableBindingSource.EndEdit()
RecTableTableAdapter.Update(VideoDBDataSet.RecTable)
RecTableAdapterManager.UpdateAll(VideoDBDataSet)
RecTableTableAdapter.Fill(VideoDBDataSet.RecTable)
VideoDBDataSet.AcceptChanges()
Else
'No row selected to work with
End If
End Sub
'The pAddForm MUST be open for this routine to work
Private Sub UpdateGridFromForm()
Dim RowIndex As Int32
Dim Index As Int32
Dim RecIndex As Int32
Dim dt As DataTable
If ((pAddForm Is Nothing) = False) Then
RowIndex = pAddForm.GridIndex
If (RowIndex >= 0) Then
Index = pAddForm.Index
If (Index = dgvRec.Rows(RowIndex).Cells(constRecGridColIndex).Value) Then
'OK, we have a match so we are good to go
Call PopulateGridFields(RowIndex)
Else
MsgBox("Unable to save data back to the Grid because the record is no longer the same")
End If
Else
'This must be a NEW record
Call AddRecord()
End If
Else
'No form to work with
End If
End Sub
'Populate the dgvRec fields from pAddForm
Private Sub PopulateGridFields(RowIndex As Int32)
dgvRec.Rows(RowIndex).Cells(constRecGridTitle).Value = pAddForm.tTitle.Text
dgvRec.Rows(RowIndex).Cells(constRecGridCast).Value = pAddForm.tCast.Text
dgvRec.Rows(RowIndex).Cells(constRecGridAKA).Value = pAddForm.tAKA.Text
dgvRec.Rows(RowIndex).Cells(constRecGridRelated).Value = pAddForm.tRelated.Text
dgvRec.Rows(RowIndex).Cells(constRecGridGenre).Value = pAddForm.tGenre.Text
dgvRec.Rows(RowIndex).Cells(constRecGridRated).Value = pAddForm.tRated.Text
dgvRec.Rows(RowIndex).Cells(constRecGridRelease).Value = pAddForm.tRelease.Text
dgvRec.Rows(RowIndex).Cells(constRecGridLength).Value = pAddForm.tLength.Text
dgvRec.CommitEdit(RowIndex)
dgvRec.EndEdit()
Validate()
RecTableBindingSource.EndEdit()
RecTableTableAdapter.Update(VideoDBDataSet.RecTable)
RecTableAdapterManager.UpdateAll(VideoDBDataSet)
RecTableTableAdapter.Fill(VideoDBDataSet.RecTable)
VideoDBDataSet.AcceptChanges()
End Sub
'This all works great.
'The only problem I have now is that the DataGridView will
'always'Repopulate the grid (including any changes with 'Add/Delete/Modify) sending the active
'row back to the top of the grid
'I will work on a solution to this now that I have the rest working

get ID from datagridview and show the data to another form in textboxes

Im kind of new in vb.net. I have a datagridview that shows the Delivery Number, Date and supplier. Now, I want the Admin to view the details of every delivery to another form. I just want to know how will I get the id of the selected row and then will be able to display the equivalent data of that selected ID. Thanks.
Here's my code for the Deliveries Form.
Private Sub dgvDeliveryReport_CellContentDoubleClick(sender As Object, e As DataGridViewCellEventArgs) Handles dgvDeliveryReport.CellContentDoubleClick
If e.RowIndex < 0 Then Exit Sub
Dim id As Int32 = dgvDeliveryReport.CurrentRow.Cells(0).Value
Dim viewDelivery As New frmDeliveryFormReport
frmDeliveryFormReport.Show()
End Sub
In your frmDeliveryFormReport class add a new field to store current row:
private _currentDeliveryReportRow as DataGridViewRow
Look for the constructor:
Public Sub New frmDeliveryFormReport()
...
End Sub
(If you cannot find it just proceed with the next step).
Change/Add the constructor so it takes the DataGridViewRow parameter and store the given row:
Public Sub New frmDeliveryFormReport(deliveryReportRow as DataGridViewRow)
_currentDeliveryReportRow = deliveryReportRow
End Sub
Adapt your existing dgvDeliveryReport_CellContentDoubleClick to call the new constructor:
Private Sub dgvDeliveryReport_CellContentDoubleClick(sender As Object, e As DataGridViewCellEventArgs) Handles dgvDeliveryReport.CellContentDoubleClick
If e.RowIndex < 0 Then Exit Sub
Dim viewDelivery As New frmDeliveryFormReport(dgvDeliveryReport.CurrentRow)
frmDeliveryFormReport.Show()
End Sub
You can then access all columns of the DeliveryReportRow in the frmDeliveryFormReport via
_currentDeliveryReportRow.Cells(<CellIndex>)
Additional information about this topic:
Passing variables between windows forms in VS 2010
VB.Net Passing values to another form
http://www.dreamincode.net/forums/topic/332553-passing-data-between-forms/
Try.
Dim newFrmName as new yourForm
For each row as DataGridViewRow in SampleGrid
if row.selected = true then
Dim whatValueYouWant as string = row.cells("ID").value.toString()
if newFrmName.NameOfTextBoxInForm.Text <> vbEmpty Then
'NameOfTextBoxInForm is textbox that existing in yourform
newFrmName.NameOfTextBoxInForm.text = ", " & whatValueYouWant
Else
newFrmName.NameOfTextBoxInForm.text = whatValueYouWant
End If
End IF
Next
newFrmName.Show()