Edit Selected Datagridview Row vb.Net - vb.net

I have a Datagridview grid with four columns. When a cell is double-clicked, the data on the selected row is passed to four textboxes for the user to make changes if any.So how do i pass the changes made to the selected row instead of having the changes added as new row?
P.S. The Data isn't from a database

You can either "remember" the DataGridViewRow by setting a module-level variable, or you can find the row again by looking for its primary key.
Public Class Form1
'Add to form:
' DataGridView called DataGridView1
' 4 Textboxes called TextBox1, TextBox2, TextBox3, and TextBox4
' Button called btnEdit
' Button called btnSave
Private mintRowWeAreEditing As Integer = -1
Private Sub btnEdit_Click(sender As Object, e As EventArgs) Handles btnEdit.Click
If DataGridView1.DataSource Is Nothing Then
'set initial data
Dim dtb As New DataTable
dtb.Columns.Add("Col1")
dtb.Columns.Add("Col2")
dtb.Columns.Add("Col3")
dtb.Columns.Add("Col4")
dtb.Rows.Add("R1C1", "R1C2", "R1C3", "R1C4")
dtb.Rows.Add("R2C1", "R2C2", "R2C3", "R2C4")
dtb.Rows.Add("R3C1", "R3C2", "R3C3", "R3C4")
dtb.Rows.Add("R4C1", "R4C2", "R4C3", "R4C4")
DataGridView1.DataSource = dtb
End If
'copy data from grid to textboxes
mintRowWeAreEditing = DataGridView1.CurrentCell.RowIndex
Dim drw As DataRow = DirectCast(DataGridView1.Rows(mintRowWeAreEditing).DataBoundItem, DataRowView).Row
TextBox1.Text = drw("Col1").ToString
TextBox2.Text = drw("Col2").ToString
TextBox3.Text = drw("Col3").ToString
TextBox4.Text = drw("Col4").ToString
End Sub
Private Sub btnSave_Click(sender As Object, e As EventArgs) Handles btnSave.Click
'copy data from textboxes to grid
If mintRowWeAreEditing = -1 Then Exit Sub 'haven't clicked Edit button yet
Dim drw As DataRow = DirectCast(DataGridView1.Rows(mintRowWeAreEditing).DataBoundItem, DataRowView).Row
drw("Col1") = TextBox1.Text
drw("Col2") = TextBox2.Text
drw("Col3") = TextBox3.Text
drw("Col4") = TextBox4.Text
End Sub
End Class

So, for example, you could do something like this on your button click event.
Private Sub btnUpdate_Click(sender As Object, e As EventArgs) Handles btnUpdate.Click
Dim refNo As Integer = txtRefNo.Text ' Change DataType and TextBox name as appropriate
Dim firstName as String = txtFName.Text
' Repeat setting variables for each field in the row that you're updating
For Each dgr As DataGridViewRow in DataGridView1.Rows
If dgr.Item("RefNo") = refNo Then
dgr.Cells(0).Value = firstName 'Instead of using (0) you can use the column name
dgr.Cells(1).Value = newVar
End If
Next
' Commit the changes/refresh here
End Sub
I don't have the IDE to hand to test this but any problems let me know, I'll have a look into it.

Related

ifselectedindex changed , show data in a textbox

I've linked an access database to my form.
I have 1 table , 2 rows
1 = Researchtype short text
2 = Researchdetails (long text)
In my combobox1 i've binded my researchtype row so i can choose a type of research.
Question now: how can i bind the details data to the richtextbox below it in order to show the research data as soon as i choose a research type?
I've tried if else combos, try catch combos,
i'm thinking i'm actually overthinking the issue here.
What would be the easiest way to "select from dropdown" and show the result in textbox.
I'm a vb.net beginner
Public Class Onderzoeken
Private Sub Onderzoeken_Load(sender As Object, e As EventArgs) Handles MyBase.Load
'TODO: This line of code loads data into the 'PatientenDatabaseDataSetX.tbl_OnderzoeksTypes' table. You can move, or remove it, as needed.
Me.Tbl_OnderzoeksTypesTableAdapter.Fill(Me.PatientenDatabaseDataSetX.tbl_OnderzoeksTypes)
End Sub
Private Sub cboxOnderzoek_SelectedIndexChanged(sender As Object, e As EventArgs) Handles cboxOnderzoek.SelectedIndexChanged
If cboxOnderzoek.SelectedItem = Nothing Then
cboxOnderzoek.Text = ""
Else
rtbBeschrijvingOnderzoek.Text = CStr(CType(cboxOnderzoek.SelectedItem, DataRowView)("OZ_Onderzoeksbeschrijving"))
End If
End Sub
End Class
I added the entire code of that page now , it's not much, but as stated: I added the binding source and displaymember "researchtype" to the combobox.
So when i start the form, i can choose a type of research.
Now i need to show the description of the research in the richtextbox
In the Form.Load...
I have a function that returns a DataTable that contains columns called Name and Type. I bind the ComboBox to the DataTable and set the DisplayMember to "Name". Each Item in the ComboBox contains the entire DataRowView. I set the TextBox to the first row (dt(0)("Type")) Type column value so the correct information will be displayed for the initial selection.
I put the code to change the textbox display in ComboBox1.SelectionChangeCommitted because the other change events will produce a NRE since .SelectedItem has not yet been set when the form loads. The commited event will only occur when the user makes a selection.
First, cast the SelectedItem to its underlying type, DataRowView. Then you want the value of the Type column. This value is assigned to the text property of the textbox.
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Dim dt = LoadCoffeeTable()
ComboBox1.DataSource = dt
ComboBox1.DisplayMember = "Name"
TextBox1.Text = dt(0)("Type").ToString
End Sub
Private Sub ComboBox1_SelectionChangeCommitted(sender As Object, e As EventArgs) Handles ComboBox1.SelectionChangeCommitted
TextBox1.Text = DirectCast(ComboBox1.SelectedItem, DataRowView)("Type").ToString
End Sub
Just substitute Researchtype for Name and Researchdetails for Type.
After using 'OleDbDataAdapter' to fill the dataset, you can set 'DisplayMember' and 'ValueMember' for your ComboBox. Every time the index of your ComboBox changes, it's 'ValueMember' will be displayed in richtextbox.
Here's the code you can refer to.
Private dataset As DataSet = New DataSet()
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Dim connString As String = "your connection String"
Using con As OleDbConnection = New OleDbConnection(connString)
con.Open()
Dim cmd As OleDbCommand = New OleDbCommand()
cmd.Connection = con
cmd.CommandText = "SELECT Researchtype, Researchdetails FROM yourtable"
Dim adpt As OleDbDataAdapter = New OleDbDataAdapter(cmd)
adpt.Fill(dataset)
End Using
ComboBox1.DisplayMember = "Researchtype"
ComboBox1.ValueMember = "Researchdetails"
ComboBox1.DataSource = dataset.Tables(0)
End Sub
Private Sub ComboBox1_SelectedIndexChanged(sender As Object, e As EventArgs) Handles ComboBox1.SelectedIndexChanged
RichTextBox1.Text = ComboBox1.SelectedValue.ToString()
End Sub
Result of my test.

VB.NET - Datagridview combobox filter and null value

I've read this post DataGridView Cascading/Dependent ComboBox Columns and I've make the same project with datagridview and 2 column combobox where the second combobox is filter by selection of first combobox.
I wuold like to have a possibility do cancel selection in second combobox, if a user select for error a second combobox can clear a selection...
Here there are a code that I used:
1) first combobox is FASE
2) second combobox is SOTTOFASE
Private Sub DataGridView1_EditingControlShowing(sender As Object, e As DataGridViewEditingControlShowingEventArgs) Handles DataGridView1.EditingControlShowing
Dim grid = DirectCast(sender, DataGridView)
If (grid.CurrentCell.ColumnIndex = 1) Then 'State column
Dim combo = DirectCast(e.Control, DataGridViewComboBoxEditingControl)
If (grid.CurrentRow.Cells(0).Value IsNot DBNull.Value) Then
Dim dvStates = New DataView(MondoDBDataSet1.Tables("SOTTOFASI"), $"n_fase = '{grid.CurrentRow.Cells(0).Value}'", "n_fase ASC", DataViewRowState.CurrentRows)
combo.DataSource = dvStates
combo.ValueMember = "n_sottofase"
combo.DisplayMember = "sottofase"
Else
combo.DataSource = Nothing
End If
End If
End Sub
Thanks for help!
This is an image of 3 step:
Datagridview steps
SOLUTION:
I have implement event KeyUp and set cell value to "dbnull" when I press button "del"
Private Sub DataGridView1_KeyUp(sender As Object, e As KeyEventArgs) Handles DataGridView1.KeyUp
If GetAsyncKeyState(Keys.Delete) Then
Dim CellCombo As DataGridViewComboBoxCell
If DataGridView1.Rows(DataGridView1.CurrentRow.Index).Cells(1).Value <> -1 Then
CellCombo = DataGridView1.Rows(DataGridView1.CurrentRow.Index).Cells(1)
CellCombo.Value = DBNull.Value
End If
End If
End Sub

VB.NET: How to copy selected cell data to the first selected cell in other form?

My question may be confusing but here is the step by step process of the output I want to accomplish.
first when I click a cell in the fist form, another form pop's up. see images..
Image 1 Image 2
then if I click the cell data of the second form it should copy the selected row data of Code and Short Name to the first datagridview cell in form 1
Here is my code so far:
Private Sub SearchJournalGrid_CellContentDoubleClick(sender As Object, e As DataGridViewCellEventArgs) Handles SearchJournalGrid.CellContentDoubleClick
With GeneralJournal
.GridJournal.Rows(.GridJournal.SelectedRows(0).Index).Cells("Code").Value = SearchJournalGrid.Rows(SearchJournalGrid.SelectedRows(0).Index).Cells("CODE").Value.ToString
.GridJournal.Rows(.GridJournal.SelectedRows(0).Index).Cells("Account Name").Value = SearchJournalGrid.Rows(SearchJournalGrid.SelectedRows(0).Index).Cells("Short Name").Value.ToString
End With
End Sub
Let me know if I got it right!
Start a new project with only two forms in it, Form1 & Form2, add a DataGridView in each with their original name, which will DataGridView1 by default.
I have created 3 columns for each of them.
The code which has placed on the only Form1 is in the following:
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
For i As Integer = 0 To 5
DataGridView1.Rows.Add(New String() {i + 1, "ITEM " & i + 1, "Description " & i + 1})
Next
End Sub
Private Sub DataGridView1_CellClick(sender As Object, e As DataGridViewCellEventArgs) Handles DataGridView1.CellClick
Dim ROW_ID As Integer = DataGridView1.CurrentCell.RowIndex
Dim DGV_Row As DataGridViewRow = DataGridView1.Rows(ROW_ID).Clone
For J As Integer = 0 To DGV_Row.Cells.Count - 1
DGV_Row.Cells(J).Value = DataGridView1.Rows(ROW_ID).Cells(J).Value
Next
With Form2
.DataGridView1.Rows.Clear()
.DataGridView1.Rows.Add(DGV_Row)
End With
Form2.Show()
End Sub

vb.net get an only one datatable row value cell and compare it with a textbox

How to get a only one datatable row cell value ? i need to comparison it with a textbox.
Like this:
If dttest.Rows.Count < 2 Then
For counter As Integer = 0 To dttest.Rows.Count - 1
If TextBox1.Text = MyDataTable.Rows(1).RowName ' but doesn't accept this format
Process.Start("http:\\www.google.it")
End If
Next
End If
UPDATE Full code:
Public Class Form2
Private dttest As DataTable
Private Sub TextBox1_TextChanged(sender As Object, e As EventArgs) Handles TextBox1.TextChanged
Dim dvtest As New DataView
dvtest = dttest.DefaultView
dvtest.RowFilter = "test Like '%" + TextBox1.Text + "%'"
End Sub
Private Sub Form2_Load(sender As Object, e As EventArgs) Handles MyBase.Load
ListBox1.DataSource = Getdata()
ListBox1.DisplayMember = "test"
End Sub
Private Function Getdata() As Object
dttest = New DataTable()
dttest.Columns.Add("test", GetType(String))
dttest.Rows.Add("test1")
dttest.Rows.Add("test2")
Return dttest
End Function
End Class
How can i get a single row value, for example, the dttest.Rows.Add("test1") ?
If your DataTable looks like this :
ColumnName1 ColumnName2
value1 hello
value2 my name is
value3 username
If you want to compare your TextBox1.Text with the 2nd column of the 3rd row, then you can use :
Dim searchedValue As String = Nothing
searchedValue = MyDataTable1.Rows("value3").Item("ColumnName2").ToString
If TextBox1.Text = searchedValue
Process.Start("http:\\www.google.it")
End If
I hope it helped.
EDIT :
' First, you create your DataTable with this function
Private Function GetData() As Object
Dim dttest As New DataTable()
dttest.Columns.Add("test", GetType(String))
dttest.Rows.Add("test1")
dttest.Rows.Add("test2")
' If you want to get the first value (firstRow and firstColumn)
' MsgBox(dttest.Rows(1).Item(0).ToString) ' you will get test1
' If you want to get the second value (secondRow and firstColumn)
' MsgBox(dttest.Rows(2).Item(0).ToString) ' you will get test2
Return dttest
End Function
Then, when you have to handle the TextChanged event on your TextBox1 to know when the user modify the text of your TextBox1.
Public Sub textBox1_TextChanged() Handles TextBox1.TextChanged
If dttest.Rows.Count <= 2 Then
For counter As Integer = 0 To dttest.Rows.Count - 1
If dttest.Rows(counter).Item(0).ToString = TextBox1.Text Then
Process.Start("http://google.it")
End If
Next
End If
End Sub

Pass variable to new form with Datatable and Listbox

I am currently trying to write an application like address book. Listbox works properly, it shows everything corretly. But I need to pass id of chosen listbox item to another form. I got code like this in Form2:
Private myTable As New DataTable()
Public Sub LoadXml(sender As Object, e As EventArgs) Handles Me.Load
With myTable.Columns
.Add("DisplayValue", GetType(String))
.Add("HiddenValue", GetType(Integer))
End With
myTable.DefaultView.Sort = "DisplayValue ASC"
ListBox1.DisplayMember = "DisplayValue"
ListBox1.ValueMember = "HiddenValue"
ListBox1.DataSource = myTable
Dim doc As New Xml.XmlDocument
doc.Load("c:\address.xml")
Dim xmlName As Xml.XmlNodeList = doc.GetElementsByTagName("name")
Dim xmlSurname As Xml.XmlNodeList = doc.GetElementsByTagName("surname")
Dim xmlId As Xml.XmlNodeList = doc.GetElementsByTagName("id")
For i As Integer = 0 To xmlName.Count - 1
Dim nazwa As String = xmlName(i).FirstChild.Value + " " + xmlSurname(i).FirstChild.Value
myTable.Rows.Add(nazwa, xmlId(i).FirstChild.Value)
MsgBox(myTable.Rows(i).Item(1).ToString)
Next i
ListBox1.Sorted = True
End Sub
Later in the code I have event:
Public Sub ListBox1_DoubleClick(sender As Object, e As EventArgs) Handles ListBox1.DoubleClick
End Sub
I would like to know how can I call id from DataTable for selected listbox item. I hope u understand what I mean since my english is not perfect :)
Since you have added the XML value id to the data table column HiddenValue and you have assigned HiddenValue as the ValueMember for the listbox, once a record is selected in the listbox, id will be available in the listbox's [SelectedValue][1] member. For example:
Public Sub ListBox1_DoubleClick(sender As Object, e As EventArgs) Handles ListBox1.DoubleClick
MsgBox("Selected Id: " & ListBox1.SelectedValue.ToString())
End Sub