I want to search record based on following fields
P_num ,P_name, P_dob,P_code
I am using more than 4 tables to retrive data,
I have created dataset called P_search and i want to fill data into dataset and thsn display it according to which field is selected for search purpose.
Suggest me to write code by creating own function in which all fields and a boolean variable will be taken as parameters
Please help me to write code using VB.net.
I am very new to VB.net. Is ther anyone who can help me giving above code.
Thank You In advance
You use DataTable.Select Method
Private Sub GetRowsByFilter()
Dim table As DataTable = DataSet1.Tables("Orders")
' Presuming the DataTable has a column named Date.
Dim expression As String
expression = "Date > #1/1/00#"
Dim foundRows() As DataRow
' Use the Select method to find all rows matching the filter.
foundRows = table.Select(expression)
Dim i As Integer
' Print column 0 of each returned row.
For i = 0 to foundRows.GetUpperBound(0)
Console.WriteLine(foundRows(i)(0))
Next i
End Sub
Related
I'm not sure if what I'm trying to do here is possible. I've got a Sheridan SSDB Grid, which is bound to a data control. When I populate the data control, the grid gets filled.
However, I've had to manually add an additional column after populating the grid to display a value which isn't in a database table.
To do all of this, I've written this code:
Dim SQL As String
SQL = My_Query
dtaEmployees.DatabaseName = DB_Period_Name$
dtaEmployees.RecordSource = SQL
dtaEmployees.Refresh
dtaEmployees.Recordset.MoveFirst
grdEmployees.Redraw = True
grdEmployees.Columns.Add (4)
I'm not sure how I can fill this new column in, however. I've got a global variable storing the value that I need, but none of the following lines of code are working
grdEmployees.Columns(4).Value = My_Variable
grdEmployees.Columns(4).Text = My_Variable
How can I set the value for all of the rows in the grid?
EDIT
After following the suggestion in the comments, I've modified my code as follows.
Form load:
Dim dbsPeriod As Database
Dim tdfEmployees As TableDef
Dim fldLoop As Field
Set dbsPeriod = OpenDatabase(DB_Period_Name$)
Set tdfEmployees = dbsPeriod.TableDefs!Ledger
AppendDeleteField tdfEmployees, "APPEND", "Location", dbText, 8
grdEmployees.DataSource = tdfEmployees
AppendDeleteField tdfEmployees, "DELETE", "Location"
dbsPeriod.Close
AppendDeleteField sub:
Private Sub AppendDeleteField(tdfTemp As TableDef, strCommand As String, _
strName As String, _
Optional varType, Optional varSize)
With tdfTemp
If .Updatable = False Then
MsgBox "Failed to initialise grid!"
Exit Sub
End If
If strCommand = "APPEND" Then
.Fields.Append .CreateField(strName, varType, varSize)
Else
If strCommand = "DELETE" Then .Fields.Delete strName
End If
End With
End Sub
With this code, no data is loaded into the grid at all.
You're not loading the data into the RecordSet before you delete the field. You need to get the data (using your SELECT query) into a data structure which the grid can use as the .DataSource
A TableDef is not a data structure, it just allows you to make changes to the database table itself, which is why your code isn't returning any rows.
Say you had a table in SQL and you wanted to find all the rows where a particular column could be one of 3 options. You could write something like this:
SELECT * FROM MyTable WHERE uid IN (123, 456, 789)
That's effectively what I want to do with a DataTable in VB. I saw this post:
Query rows that the datatable field contain any item in the list<string>
Which seemed to be exactly what I wanted, but it's not working as I expected it to. I basically just used a C# -> VB converter and plugged in my variables and came up with this:
Dim item = From a In dtCodes.AsEnumerable() Where
lstCodes.Any(Function(x) a.Field(Of String)
("Code").ToUpper().Contains(x.ToUpper())) Select a
dtCodes is a DataTable with a column Codes in it. lstCodes is a List(Of String) with some values in it.
item just has all of the rows from dtCodes though, regardless of whether or not their Code column value exists in lstCodes.
What am I missing?
edit; Note that I don't have to use LINQ, if there's an easier or better way.
In the past, I've done this sort of like this:
Dim item = From r as DataRow in dtCodes.Rows
Where lstCodes.contains(r.Item("Codes"))
Select r
Does that work?
The code you have looks ok to me. I tried out this test and it (correctly) prints out
a2
b1
Dim dtCodes As New DataTable
dtCodes.Columns.Add(New DataColumn("Code"))
dtCodes.Rows.Add("a1")
dtCodes.Rows.Add("a2")
dtCodes.Rows.Add("b1")
dtCodes.Rows.Add("b2")
Dim lstCodes As New List(Of String)
lstCodes.Add("b1")
lstCodes.Add("c1")
lstCodes.Add("a2")
Dim item = From a In dtCodes.AsEnumerable()
Where lstCodes.Any(Function(x) a.Field(Of String)("Code").ToUpper().Contains(x.ToUpper()))
Select a
For Each itm In item
Debug.WriteLine(itm("Code").ToString)
Next
Here's a lamba expression that should also work.
Dim item = dtCodes.Select.Where(Function(x As DataRow) lstCodes.Contains(x.Item("Codes")))
Good morning stackers!
I'm designing a massive update page. Here are the general steps:
I have a class called item which has two properties: Equipment number and new due date.
I have a textbox where i paste values from Excel, the values consist of two columns divided by a vbtab character: the columns are an equipment number and a new due date
A button is clicked and the values from textbox are parsed into a list(of item) and the equipment master builds a string for an SQL criteria for a commandtext.
The command fills a dataset from a database which gets equipment number and current due date.
I add manually a column to the dataset (new due date)
I iterate over the rows of the dataset, and i use the list(of item) find method matching equipment from the list and from the database to get a new due date from the textbox parsed values.
Everything is going well, except that when using the find method for more than 1 row in the dataset, the method fails:
Here is the code from point 5 and 6:
da.Fill(ds, "Equipments")
dt = ds.Tables(0)
ds.Tables(0).Columns.Add("column_1", Type.GetType("System.DateTime"))
Dim rw As DataRow
For Each rw In ds.Tables(0).Rows
Dim strsearch As String = rw(0).ToString
Dim fequnumb As item = myItemList.Find(Function(p) p.EquipNumber = strsearch)
rw(2) = fequnumb.DueDate <- Error occurs here
Next
Again, if instead of ftechid.DueDate I put a static value like Today()the code runs fine for the loop and fills correctly the gridview, but if i leave the ftechid.DueDate then an error is thrown after the first row:
Object reference not set to an instance of an object.
Any help is very much appreciated as to how to use the find method inside a for..each loop
If the Find function cannot match the string requested it returns Nothing and then you cannot set the due date from a variable that is Nothing. If this is a condition expected from the input then you need to protect the assignment to the new column with something like this.
For Each rw In ds.Tables(0).Rows
Dim strsearch As String = rw(0).ToString
Dim fequnumb As item = myItemList.FirstOrDefault(Function(p) p.EquipNumber = strsearch)
if fequnumb IsNot Nothing Then
rw(2) = fequnumb.DueDate <- Error occurs here
End if
Next
If this is not supposed to happen then you need to check your inputs
I have an asp.net listbox on my page, that I want to sort.
E.g: listbox(lstChooseFields)
MY VB code:
Private Sub LoadColumns()
If drpScreen.SelectedIndex > -1 Then
Dim daLookup As New LookupTableAdapters.LookupTableAdapter
Dim dtLookup As New System.Data.DataTable
dtLookup = daLookup.GetNestedControlValues("EM", "ExcelExport.aspx", "drpScreen", "drpScreen", drpScreen.SelectedValue)
lstChooseFields.DataSource = dtLookup
lstChooseFields.DataValueField = "LKP_ControlValue"
lstChooseFields.DataTextField = "LKP_ControlText"
lstChooseFields.DataBind()
'Dispose
daLookup.Dispose()
End If
End Sub
I have done some searching and found something like 'dtLookup.DefaultView.Sort = "LKP_ControlText" that I can use but it does not work. I don't want to sort in my database only on this page, this listbox (lstChooseFields).
So if you want to sort for the datatable then you have tried dtLookup.DefaultView.Sort = "LKP_ControlText" but you have missed out one piece of word there dtLookup.DefaultView.Sort = "LKP_ControlText asc". This generally works if LKP_ControlText is a column name in the datatable
You must use the word ascthere. which i couldnt find in your question.
After getting the dataTable sorted you can copy the same structure to another datatable if u want by using
Dim dtDuplicateLookup As New DataTable()
dtDuplicateLookup = dtLookup.DefaultView.ToTable(True)
and then access dtDuplicateLookup for further use if you want to retain the previous datatable as it is.
Use the .sorted property for the list box as shown here.
lstChooseFields.Sorted = True
UPDATE: your method was right but just tune it this way. I think you missed the DESC part. The second expression tells it how to sort the dataview.
Dim dataView As New DataView(table)
dataView.Sort = " column_name DESC" //DESC or ASC as per requirement
Dim dataTable AS DataTable = dataView.ToTable()
Else try this. After sorting a defaultview, generally you have to loopback through it
foreach(DataRowView r in table.DefaultView)
{
//... here you get the rows in sorted order
//insert the listbox items one by one here using listbox.add or listbox.insert commands
}
I am using DataTable.Select() method to filer based on some conditions.
dtRows = m_dtTable.Select(String.Format("IdentifierID={0}", dtRow
("QuestionID").ToString))
I used the similar way to sort the data in different places . But only one place i am getting error.
Can any help me to find why this exception is occurs? Also help me to know why there is no exception in other places ? The values of datatable is filled from a stored procedure.
Min (2) must be less than or equal to max (-1) in a Range object. is exception I am getting.
EDIT -- After the First Answer --
I am getting exception not every time, but only some time that I cannot identify the scenario. :(
ADDED -- After the First Answer --
Thanks for the solution. :)
Note : m_DependantQuestionsDataTable and m_dtTable are same by its schema.
colIdentifierID.DataType = Type.GetType("System.String")
colIdentifierID.ColumnName = "IdentifierID"
This is the type of particular column. There is also another column which is also similar type and there is no error occurs when I use it with the similar method.
colQuestionID.DataType = Type.GetType("System.String")
colQuestionID.ColumnName = "QuestionID" is the column and I am using like this. ' Dim strFilterExpression As String = "questionID={0}" m_DependantQuestionsDataTable.Select(String.Format(strFilterExpression, dRow("QuestionID")))'
Here there is no exception or error is occurring . So if I am choosing your solution I need to change the Filter Expression by adding ' in all place in my solution where I am using Filter Method.
You don't specify the data type of the column you're filtering on and if it's a string then you'll need to add single quotes around the parameter in your filter expression:
dtRows = m_dtTable.Select(String.Format("IdentifierID='{0}'", dtRow("QuestionID").ToString()))
alternatively, if you want to sort+ filter via the DGV, without need to repopulate the DT and DGV, you can use .Sort and .RowFilter of the DataView
http://msdn.microsoft.com/en-ca/library/system.data.dataview.rowfilter.aspx
Private _DS As New DataSet
Private _DT As New DataTable
Private _DV As New DataView
Private _DGV As New DataGridView
Private _isFiltering As Boolean = False
Private Sub filterView()
If _isFiltering Then Return
_isFiltering = True
Dim _SF As String = "price ASC"
'Dim _RF As String = tableStructure.Columns(0).Name & " < 20" ' just an example
Dim _RF As String = "price < 20"
_DGV.ClearSelection()
_DT.DefaultView.Sort = _SF
_DT.DefaultView.RowFilter = _RF
_isFiltering = False
End Sub