Get the BindingSource position based on DataTable row - vb.net

I have a datatable that contains the rows of a database table. This table has a primary key formed by 2 columns.
The components are assigned this way: datatable -> bindingsource -> datagridview. What I want is to search a specific row (based on the primary key) to select it on the grid. I cant use the bindingsource.Find method because you only can use one column.
I have access to the datatable, so I do manually search on the datatable, but how can I get bindingsource row position based on the datatable row? Or there is another way to solve this?
Im using Visual Studio 2005, VB.NET.

I am attempting to add an answer for this 2-year old question. One way to solve this is by appending this code after the UpdateAll method(of SaveItem_Click):
Me.YourDataSet.Tables("YourTable").Rows(YourBindingSource.Position).Item("YourColumn") = "YourNewValue"
Then call another UpdateAll method.

Well, I end up iterating using bindingsource.List and bindingsource.Item. I didnt know but these properties contains the data of the datatable applying the filter and sorting.
Dim value1 As String = "Juan"
Dim value2 As String = "Perez"
For i As Integer = 0 To bsData.Count - 1
Dim row As DataRowView = bsData.Item(i)
If row("Column1") = value1 AndAlso row("Column2") = value2 Then
bsData.Position = i
Return
End If
Next

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

How to filter a datagridview when using data from datatable? VB.net

I have created a textbox and want it to search through a database of customers by name. Most of the questions are using an external dataset but this is just using a table created in the program using a csv file.
You could take advantage from BindingSource, to be used as DataSource of your DataGridView. That way, acting on the BindingSource Filter property, you could set any type of filters, based on you columns name.
Please check the following snippet:
Dim dt As New DataTable("Sample")
dt.Columns.Add("Id")
dt.Columns.Add("TimeStamp")
For i As Int32 = 0 To 9999
dt.Rows.Add(New Object() {i, DateTime.Now})
Next
Dim bs As New BindingSource
bs.DataSource = dt
bs.Filter = "Id > 10 AND Id < 20"
DataGridView1.DataSource = bs
As you can see, i've defined a DataTable with two columns, namely "Id" and "TimeStamp". Then, with a simple loop i've populated my DataTable with some random records, for Id = 0 to Id = 9999.
After that, we declare a BindingSource, specifying its DataSource is our DataTable. On the Bindinf Source, we could set any filter, using the Filter property, the columns names, and the common logical operators.
In my example, i've requested the filter to be on the only Id column, to visualize those record whose Id is between 11 and 19.
Then, we could use the BindingSource as our DataGridView DataSource.
And note that filters doesn't need to be apply before assigning the DataGridView DataSource: in fact, after the binding, each filter application will reflect immediately on the visualized rows.
Hope this helps

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

How can I display column names of one table in a combobox?

In vb.net 2008, how can I display table column names in a combobox?
In SQL I have a Document table and there are columns in this table like Doc_id, Size, Path.
The combobox must display the columns name like
doc_id in the first line, size in the second line, path in the last line
Probably a little too late since I see this thing is about eight years old, but I just ran into this issue where I had to do exactly what the initial questioner was asking for. Since I resolved it, I will leave it here just incase another poor sap like us comes along looking for answers
'VB.net
Dim ds As DataSet = <define your dataset here>
Dim dt As DataTable = ds.Tables(<Your tablename here>)
For Each column As DataColumn In dt.Columns
combobox1.Items.Add(column.ColumnName)
Next
As per our discussion , i will suggest you not to bind the combobox directly with the DataTalble. you can bind it by looping all the row of the DataTable. you use following snipped as a reference:
Dim objDataTable As DataTable = ds.Tables("Document")
IF objDataTable <> NULL Then
For j As Integer = 0 To objDataTable.Rows.Count
Dim str As String = objDataTable.Rows(j)("Doc_id").ToString()
comboBox1.Items.Add(str)
str = objDataTable.Rows(j)("Size").ToString()
comboBox1.Items.Add(str)
str = objDataTable.Rows(j)("Path").ToString()
comboBox1.Items.Add(str)
Next
END IF
Hope this will work for you ;)

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.