Error while using DataTable.Select() Method in Vb.Net - asp.net

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

Related

How can I store the y value of a chart series in a label on my page?

I am curious how I can access the value of a YValueMember in a chart that I am populating through a database and display that value in a label. Basically I want to set a labels text equal to the y value of my chart.
I am populating my chart through a db query and setting the YValueMembers to the alias I use within my query
SELECT ( SELECT SUM(DealerNet) FROM Agreement WHERE VoidDate IS NULL
AND IssueDate BETWEEN #PFOM AND #date) AS Actual,
(SELECT SUM(Amount) FROM Sales
WHERE [Year] BETWEEN YEAR(#PFOM) AND YEAR(#date)
AND [Month] BETWEEN MONTH(#PFOM) AND MONTH(#date)) AS Projected
I then pass this query to a function I have to populate a DataTable called GetData() as seen in the call below.
GetData() Function:
Private Shared Function GetData(cmdSQL As SqlCommand, ByVal Optional strCon As String = "") As DataTable
If strCon = "" Then
strCon = ConfigurationManager.ConnectionStrings("WarrantyConnectionString").ToString
End If
Dim rstData As New DataTable
Using conn As New SqlConnection(strCon)
Using (cmdSQL)
cmdSQL.Connection = conn
conn.Open()
rstData.Load(cmdSQL.ExecuteReader)
End Using
End Using
Return rstData
End Function
Chart Code:
Dim cmdSQL As New SqlCommand(query)
cmdSQL.Parameters.Add("#date", SqlDbType.Date).Value = previousMonthDateToday
cmdSQL.Parameters.Add("#PFOM", SqlDbType.Date).Value = previousFirstOfMonth
pmtdChart.Series(0).ChartType = SeriesChartType.Column
pmtdChart.Series(1).ChartType = SeriesChartType.Column
pmtdChart.Legends(0).Enabled = True
pmtdChart.Series(0).XValueMember = xMember1
pmtdChart.Series(1).XValueMember = xMember2
pmtdChart.Series(0).YValueMembers = "Actual"
pmtdChart.Series(1).YValueMembers = "Projected"
lblPMTDprojected.Text = pmtdChart.Series(1).ToString()
lblPMTDbilled.Text = pmtdChart.Series(0).ToString()
pmtdChart.DataSource = GetData(cmdSQL)
pmtdChart.DataBind()
The GetData Function takes the query above and populates a DataTable, I don't know if I can pull directly from the Datatable within my function and I'm not terribly sure how I would do that, or If I need to pull the value from the chart that I am using.
I have tried the following in the Chart Code:
label.Text = Chart.Series(0).ToString
label.Text = Chart.Series(0).Points(0).ToString()
label.Text = Chart.Series(0).YValueMembers("Actual").ToString
label.Text = Chart.Series(0).YValueMembers(0).ToString
The first quite simply pulls the text value I have assigned to
pmtdChart.Series(0).YValueMembers = "Actual"
The second returns an exception error stating "Index was out of range. Must be non-negative and less than the size of the collection."
The Third returns an exception stating "Conversion From String "Text" to Type "Integer" is not valid.
And the fourth simply returns the first character of "Actual"
Technically I can simply pull this value from my database and assign it to the label, but I am wondering if there is a way to just snag it from my chart so I don't have to query the db again, considering I am using a similar query to populate the chart in the first place.
Any help or tips regarding this issue would be greatly appreciated and I feel like there should be a way to do what I am trying to do. If more information is needed I would be happy to supply it.
I was able to solve the problem I was having above by creating a second data table outside of the GetData() function and then using the GetData() function to populate the second data table. This allowed me to access the specific row/column that held the value I needed
actual = dt.Rows(0)("Actual").ToString()
projected = dt.Rows(0)("Projected").ToString()
I was then able to use these specific values where I needed them outside of the GetData() function.

ASP VB NET List(of T) find method failing in a for each loop

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

Sorting a datatable

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
}

Simple bind value to textbox in code behind using Telerik OpenAccess

I cannot find a complete example. Found tons on grid and combobox, but not textbox. This test is to lookup a “PhoneTypeName” from a UserPhoneType table with TypeCode = “0” and assign that first value to a asp.net textbox.
Currently, I am getting “Object reference not set to an instance of an object” when setting the text box to "phonetype.FirstOrDefault.PhoneTypeName.ToString"
Using dbContext As New EntitiesModel()
Dim phonetype As IEnumerable(Of User_PhoneType) = dbContext.User_PhoneTypes.Where(Function(c) c.PhoneTypeCode = "O")
mytextbox.Text = phonetype.FirstOrDefault.PhoneTypeName.ToString
End Using
----EDIT----
I changed as suggested. I ALSO successfully bound the entire list of PhoneTypes to a droplist control...to confirm the data is accessible. It must be the way I am going about querying the table for a single record here.
I get the same error, but at "Dim type = phonetype.First..."
The record is in the table, but it does not appear to be extracted with my code.
Dim phonetype As IEnumerable(Of User_PhoneType) = dbContext1.User_PhoneTypes.Where(Function(c) c.PhoneTypeCode = "M")
Dim type = phonetype.FirstOrDefault
If Object.ReferenceEquals(type, Nothing) = False And Object.ReferenceEquals(type.PhoneTypeName, Nothing) = False Then
mytextbox.Text = type.PhoneTypeName.ToString
End If
In general there are the following two possible reasons for getting this exception:
1) The phonetype list is empty and the FirstOrDefault method is returning a Nothing value.
2) The PhoneTypeName property of the first element of the phonetype list has a Nothing value.
In order to make sure that you will not get the Object reference not set to an instance of an object exception I suggest you add a check for Nothing before setting the TextBox value. It could be similar to the one below:
Dim type = phonetype.FirstOrDefault
If Object.ReferenceEquals(type, Nothing) = False And Object.ReferenceEquals(type.PhoneTypeName, Nothing) = False Then
mytextbox.Text = type.PhoneTypeName.ToString
End If
Fixed it.
I was able to view the SQL string being generated by using this:
mytextbox.text = phonetype.tostring
I saw that the SQL contained "NULL= 'O'"
I did it like the example?!? However, when I added .ToString to the field being queried, it worked.
So the final looks like this:
Using dbContext As New EntitiesModel()
Dim phonetype As IEnumerable(Of User_PhoneType) = dbContext.User_PhoneTypes.Where(Function(c) c.PhoneTypeCode.**ToString** = "O")
mytextbox.Text = phonetype.FirstOrDefault.PhoneTypeName.ToString
End Using
BTW, Dimitar point to check for null first is good advice (+1). The value was nothing as he said.

Search data from dataset

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

Resources