Getting the row number of the dataset by using datagridview's currentrow property - vb.net

please help me with this problem. I have a datagridview that is bounded to a dataset and when i select an item to the datagridview to delete, I get the correct item. But when i sorted the datagridview to some field, it return a different item. Here is my code:
DSet.Tables("sec_company_address").Rows(sec_company_address.CurrentRow.Index).Delete()
Edit: i try this line but it brings up an error.
Dim xID As String = sec_role_module.CurrentRow.Cells("nID").Value.ToString
sDataSet.Tables(sec_role_module.Name).Rows.Find(xID).Delete()

Before anything else, you must set Primary column in the sec_company_address so that DELETE will work. and try this:
' change columnName to your column which is the Unique Identifier
dim xID as string = dataGridView1.CurrentRow.Cells("columnName").Value.Tostring
DSet.Tables("sec_company_address").Rows.Find(xID).Delete()
DSet.Tables("sec_company_address").AcceptChanges()
UPDATE
how about this?
For Each xRow As DataRow In sec_role_module.SelectedRows
sDataset.Tables(sec_role_module.Name).Rows.Remove(xRow)
sDataset.AcceptChanges()
Next

By changing the sorting of your datagridview, you refer to another item in your dataset, because your dataset is still the same as the initial load.
How can you fix this?
You could use a unique identifier in your first column, which you can refer to for the deletion of the row in the dataset.

Related

Add column to DataGridView (VB.NET)

I would like to add a new column in my project, but a weird thing happened...
My code
adapter.fill(datatable)
dgv.datasource = datatable
dgv.columns.add("test","testHeader")
The column index of test column should be the last index.
However, I found the column index is 0 and the original 0th index turns to 1
I am not sure what happened. Is there any factor could cause this problem?
property settings of datagridview is wrong?
Try This Code For Adding the Column
Dim col As New DataGridViewTextBoxColumn
col.DataPropertyName = "PropertyName"
col.HeaderText = "SomeText"
col.Name = "colWhateverName"
DataGridView1.Columns.Add(col)
It's simple , get the total column count first and then add the column at the end :
Dim col as New DataGridViewColumn
col.HeaderText = "abc"
dgv.Columns.Insert(dgv.ColumnCount, col)
If the above code doesn't help , try adding column to the IDataTable itself :
datatable.Columns.Add("Header text", GetType(System.String)).SetOrdinal(datatable.Columns.Count)
Your code
adapter.fill(datatable)
dgv.datasource = datatable
dgv.columns.add("test","testHeader")
seems to be working properly.
I guess you are re-filling the datagridview that's why the added column is in index 0.
try to add
dgv.DataSource = Nothing
you will notice that the added column "test","testHeader" will be in index 0.
setting again
dgv.datasource = datatable
will cause the added column to remain at index 0 while the datatable will be added to the succeeding columns.
There's a DataGridViewColumn.DisplayedIndex property to control order of visible columns.
Keep in mind that DataGridView tracks theese values and update them for other columns in your grid. Chaning some of them to 0 will update all other columns to highter values.
This works because we clone an existing column while you cannot append a column that does already exist in a table. this also has the benefit of cloning all the column settings applied to the existing columns.
Clone a existing column:
Dim Newtestcolumn As DataGridViewColumn = Existingcolumn.Clone
Adjust header text:
Newtestcolumn.HeaderText = "test"
Add column to datagridview:
DataGridView1.Columns.Add(test)
If you add columns that does not match the current drawing format you need to update the datagridview object by calling:
DataGridView1.Update()
If you want to write to a specific column or you dont know the column name
you use this to return the amount of columns and then point to column 0 for cloning fx.
Dim Index = DataGridView1.Columns.GetColumnCount(DataGridViewElementStates.None)
You specify the column index like this:
DataGridView1.Columns.Item(index)
going back to the first line we would then write
Dim Newtestcolumn As DataGridViewColumn = DataGridView1.Columns.Item(index).clone

Clear all the value of a datagridview column once in vb.net

i have user below code to clear the cell value of a datagridview column.
For Each item As DataGridViewRow In dgvGeometricImport.Rows
item.Cells("Status1").Value = String.Empty
Next
Do we have any short cut to clear all value without iterating the rows?
can we use linq to achieve this?
thanks in advance
With or without a DataSource set, you can *remove and re-add the column.
VB Example with DataSource set:
Dim index As Integer = Me.dataGridView1.Columns("Status1").DisplayIndex
Dim table As DataTable = DirectCast(Me.dataGridView1.DataSource, DataTable)
Dim column As DataColumn = table.Columns("Status1")
table.Columns.Remove(column)
table.Columns.Add(column)
Me.dataGridView1.Columns("Status1").DisplayIndex = index
VB Example without DataSource set:
Dim index As Integer = Me.dataGridView1.Columns("Status1").Index
Dim column As DataGridViewColumn = Me.dataGridView1.Columns("Status1")
Me.dataGridView1.Columns.Remove(column)
Me.dataGridView1.Columns.Insert(index, column)
*Disclaimer: This will work, but if I'm being honest I can't say for certain that there's no iteration occurring at some lower level. After all, when you re-add the column it becomes a part of each row entry and therefore could have been iterated through under-the-hood.
One approach would be to use jQuery selectors. It would of course still iterate through the rows, but it would be done client side and behind the scene.
$('#' + gridViewCtlId + ' td:nth-child(' + INDEX_COLUMN_TO_CLEAR + ')').html('');
use this :
dataGridView.Rows.Cast(Of DataGridViewRow).ToList.ForEach(Sub(r) r.Cells("ColumnName").Value = String.Empty)
but it's the same thing, linq will do the iteration

Checking duplicate Values on DataGrid

I have a DataGrid which is bound with a DataTable having two columns which store sequences, in my DataGrid these sequence columns are bound with DataGridViewComboBoxes. User is able to set sequence from ComboBoxes. Default values in sequence columns is 0.
I just want to check duplicacy in both the columns on button click, user should not be able select any duplicate value in both the columns.
If i implement it by using ToTable method of DataView to find distinct values it also takes rows with value "0"
if i implement unique constraint on column on DataTable it also checks for 0.
If try to remove values with 0 it also changes DataGrid As DataGrid is bound with DataTable
If i try to declare a new DataTable from existing dataTable it also gets bound to DataGrid Automatically.
Please help me.
Here is an example of how you can check for duplicate values in a DataTable:
Option Strict On
Module Module1
Sub Main()
Dim dt As New DataTable
dt.Columns.Add("mycolumn", GetType(Integer))
dt.Rows.Add({"1"})
dt.Rows.Add({"2"})
dt.Rows.Add({"2"})
dt.Rows.Add({"4"})
dt.Rows.Add({"7"})
Dim duplicateDictionary As New Dictionary(Of Integer, Integer) 'value, count
For Each row As DataRow In dt.Rows
Dim count As Integer = 0
Dim value As Integer = CInt(row("mycolumn"))
duplicateDictionary.TryGetValue(value, count)
duplicateDictionary(value) = count + 1
Next
For Each kv As KeyValuePair(Of Integer, Integer) In duplicateDictionary
If kv.Value > 1 Then 'we have a duplicate
Debug.WriteLine("{0} is a duplicated value, encountered {1} times", kv.Key, kv.Value)
End If
Next
End Sub
End Module
Adding a UniqueConstraint is possible as well, but I find it too intrusive at times, depending on how your editing works. For direct in-grid editing, you may want the user to save a non-valid record in memory, and allow to fix the error, showing validation errors instead of constraint violation exception. Of course you never save invalid data to the database.

display datatable text

I have a data table with many rows and columns.
How can I display the value (text) in row 1 column 1 to a message box?
I am able to display the row count, but can't seem to figure out how to display the actual contents of the cells.
I'm using VS2012, and coding in VB
Try,
MessageBox.Show(datatabelname.rows(1)(1))
Dim myDataRow AS DataRow = myDataTable.Rows(0)
MessageBox.Show(myDataRow(0))
I think this works as well:
myDataTable.Rows(0).Field(Of String)(0)

How can I update a row in a DataTable in VB.NET?

I have the following code:
Dim i As Integer = dtResult.Rows.Count
For i = 0 To dtResult.Rows.Count Step 1
strVerse = blHelper.Highlight(dtResult.Rows(i).ToString, s)
' syntax error here
dtResult.Rows(i) = strVerse
Next
I want to add a strVerse to the current row.
What am I doing wrong?
The problem you're running into is that you're trying to replace an entire row object. That is not allowed by the DataTable API. Instead you have to update the values in the columns of a row object. Or add a new row to the collection.
To update the column of a particular row you can access it by name or index. For instance you could write the following code to update the column "Foo" to be the value strVerse
dtResult.Rows(i)("Foo") = strVerse
You can access columns by index, by name and some other ways:
dtResult.Rows(i)("columnName") = strVerse
You should probably make sure your DataTable has some columns first...
Dim myRow() As Data.DataRow
myRow = dt.Select("MyColumnName = 'SomeColumnTitle'")
myRow(0)("SomeOtherColumnTitle") = strValue
Code above instantiates a DataRow. Where "dt" is a DataTable, you get a row by selecting any column (I know, sounds backwards). Then you can then set the value of whatever row you want (I chose the first row, or "myRow(0)"), for whatever column you want.