Datarow object, why is this code working? - sql

after assign a row values of datatabe to a new data row object , any changes in this object affects on the data table , Why ?
have a look at this code.
DataRow dr = mydataset.Tables["NewTable"].Rows[0];
dr["Name"] = "hello";
Now if you try to debug your application you will find that the original data table ["NewTable"] has the new value hello instead of the old value Although we didn't return back the above data row to data table (we didn't save it )
I Just need a clarification and also need to know & understand what actually happen when i create an Object of a data row .

Both DataTable and DataRow are reference data types. This means that when you assign a variable to its reference in code, it simply holds a pointer back to the same memory location.
DataRow dr1 = mydataset.Tables["NewTable"].Rows[0];
DataRow dr2 = mydataset.Tables["NewTable"].Rows[0];
DataRow dr3 = dr1;
DataTable dt = mydataset.Tables["NewTable"];
DataRow dr4 = dt.Rows[0];
In the above example, dr1, dr2, dr3, and dr4 all point to the same memory location. Therefore if you edit dr4, the changes will appear on dr1, dr2, and dr3.
See Value Types and Reference Types for more information.

Related

Won't add a default custom row on combobox

been having an issue displaying an empty item as default selected item on a combobox. This combobox is a filter for my gridview and currently my datagridview displays all data based on the first item of the combobox but what i wanted is to have an empty first combobox item so that datagridview will pull all data from database. When i run the app it says
System.ArgumentException: 'Input string was not in a correct
format.Couldn't store <> in ailment_id Column. Expected type is
Int32.'
My code to populate combobox from database:
Private Sub populateComboAilment()
data_adapter = New MySqlDataAdapter("SELECT * FROM ailment", myconnection.open())
Dim data_table As New DataTable
data_adapter.Fill(data_table)
'assign default value
Dim row As datarow = data_table.NewRow()
row(0) = ""
data_table.Rows.InsertAt(row, 0)
comboAilment.DataSource = data_table
With comboAilment
.DisplayMember = "name"
.ValueMember = "ailment_id"
End With
myconnection.close()
End Sub
Update: All is working now when I changed combobox ValueMember to a
name since it's an id before. but when I select another item it
displays nothing on the gridview because my datagridview query doesn't
know the name, only id since it's a foreign key.
Any help would be greatly appreciated!
Ah, I just looked more carefully at the code and you're not actually assigning a String containing "<>" but rather an empty String. It doesn't really matter though. A String is a String and you can't put one where a number is required. You might be able to use a String that contained digits because that could be implicitly converted to a number but a empty String doesn't qualify.
If you want an empty field in a DataRow then you need to do what ADO.NET does to represent a database null, i.e. use DBNull.Value. That means an object of type DBNull, which is required because ADO.NET predates nullable value types. You can't just use Nothing because would work for reference types but not value types, e.g. if you assign Nothing to an Integer variable you are effectively setting it to zero.
In short, you need to change this:
Dim row As datarow = data_table.NewRow()
row(0) = DBNull.Value
row(1) = DBNull.Value
data_table.Rows.InsertAt(row, 0)
In the case of the name column, its data type is String so you could use an empty String there (preferably String.Empty rather than "" but either works) but null is more appropriate because it is actually no value, rather than a value containing no characters.

How do I query a local datatable and return information to a datatable in VB.net

I am trying to pass a query and existing datatable into a function. The function will query the passed datatable using the passed query and return the result.
Unfortunately, I am unable to return any data. I have posted my code below. Can anyone help me fix it? I don't know what I am doing wrong.
Public Function ExecQueryTest(Query As String, DT As DataTable) As DataTable
Dim Result() As DataRow
'initialize the table to have the same number of columns of the table that is passed into the function
Dim LocalTable As DataTable = DT
'initialize counting variables
Dim x, y As Integer
'use the select command to run a query and store the results in an array
Result = DT.Select(Query)
'remove all items from the localtable after initial formatting
For x = 0 To LocalTable.Rows.Count - 1
LocalTable.Rows.RemoveAt(0)
Next
'for loop to iterate for the amount of rows stored in result
For x = 0 To Result.GetUpperBound(0)
'add each array row into the table
LocalTable.Rows.Add(Result(x))
Next
ExecQueryTest = LocalTable
End Function
If there is a better way to accomplish my goal, I don't mind starting from scratch. I just want to be able to handle dynamic tables, queries, and be able to return the information in a datatable format.
The problem is here:
Dim LocalTable As DataTable = DT
That code does not do what you think it does. DataTable is a reference type, which means assigning DT to the LocalTable variable only assigns a reference to the same object. No new table is created, and nothing is copied. Therefore, this later code also clears out the original table:
'remove all items from the localtable after initial formatting
For x = 0 To LocalTable.Rows.Count - 1
LocalTable.Rows.RemoveAt(0)
Next
Try this instead:
Public Function ExecQueryTest(Query As String, DT As DataTable) As DataTable
ExecQueryTest = New DataTable() 'create new DataTable object to hold results
For Each row As DataRow In DT.Select(Query)
ExecQueryTest.LoadDataRow(row.ItemArray, True)
Next
End Function
Though you may also need to clone each DataRow record.
You can clear a table with just
LocalTable.Clear()
instead of using that cycle, Also the results of your select can be directly converted to datatable using
LocalTable = Result.CopyToDataTable

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

VB.Net Fill tables in dataset by data variables

Hi I need to fill a datatable(in data set) row by row by providing the the data by variables in VB.Net. The variables assigns its value by loop.. so the datatable row should be filled row by row until the loop ends. There are three columns in the table. so the table should fill with different kind of datatype variables. pls help.. I need the piece of code...
Sample code to do it:
Inserting a New Record into an Untyped Dataset
Dim newEmployeeRow As DataRow = DtEmployee.Tables("Employee").NewRow()
newEmployeeRow ("EmpNo") = value
newEmployeeRow ("EmpName") = value
newEmployeeRow ("Commission") = value
DtEmployee.Tables("Employee").Rows.Add(newEmployeeRow )
Inserting a New Record into a Typed Dataset
Dim newCustomersRow As NorthwindDataSet.CustomersRow
newCustomersRow = NorthwindDataSet1.Customers.NewCustomersRow()
newCustomersRow.CustomerID = "ALFKI"
newCustomersRow.CompanyName = "Alfreds Futterkiste"
NorthwindDataSet1.Customers.Rows.Add(newCustomersRow)

Get the BindingSource position based on DataTable row

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