I have table named studentlogs, and it has column status on it. When I finished inserting records on student logs, I want to use an if .. else statement. The status column can only have 3 values: 1, 2 or 3.
Now, I want to do the following after I insert the records:
if status="1" then
CALL SENDSMS()
ENDif
if status="2" then
msgbox("")
ENDif
if status="3" then
msgbox("")
How can I do it when I am dealing with columns?
To get the value of a row in a specific column, you can use parenthesis right after the row object and specify the ColumnName or ColumnIndex property to get the value.
Also, when there is more than one potential value, you can ue a case statement, instead of a lot of ElseIf statements.
MVCE Setup
'declare local variables
Dim dr As DataRow
'create table
Dim studentLogs As New DataTable("StudentLogs")
'add columns
With studentLogs
.Columns.Add("Status", GetType(Integer))
.Columns.Add("OtherCol1", GetType(String))
End With
'add values
With studentLogs
dr = studentLogs.NewRow()
dr("Status") = 1
dr("OtherCol1") = "Joey"
studentLogs.Rows.Add(dr)
End With
Check Column Value / Row Status
For Each row As DataRow In studentLogs.Rows
Select Case row("Status")
Case 1
Call SENDSMS()
Case 2
MsgBox("2")
Exit For
Case 3
MsgBox("3")
End Select
Next
Related
I'm currently selecting a bunch of values from SQL and load them into a dataTable. I'm trying to find that particular column and update the value in each rows.
Dim dt as DataTable
'not all code is included - but this definitely works on selecting data
sql = " Select value1, value2, value3 from TblA "
cmd = New SqlClient.SqlCommand(sql, conn)
Dim reader As SqlDataReader = cmd.ExecuteReader
dt.Load(reader)
return dt
My goal is to take the value from each row in VALUE3, and run it through a small Formatting function called - UpdateFormat. Something along the lines of....
Dim specValue As String
For Each row As DataRow In dt.Rows
UpdateFormat(specValue ) = row.Item("Value3")
Next row
I'm hoping to update each value and update the dataTable so it has the correct values.
In a previous episode, we learned that you want to format the data in that column from 012345678 to 012-34-5678W where the column is VarChar and the 'W' is fixed.
You can do the formatting in the SQL:
Dim sql = <sql>
SELECT Id, Foo, Bar, ColA,
CONCAT(SUBSTRING([Value3],1,3),
'-',
SUBSTRING([Value3],4,2),
'-',
SUBSTRING([Value3],6,4),
'W' ) AS NewV3Value
FROM
dbo.TableBob
</sql>.Value
Doing so, the column is delivered to you already formatted. Depending on your DB flavor, the exact syntax may vary.
The <sql>...</sql>.Value is just an XML literal which allows you to format long or complex queries in such a way that it makes it easier for you to read.
To do it yourself in the table. As the format is trivial to apply, you really dont need a method to do it:
Dim tmp As String
For Each row As DataRow In dt.Rows
tmp = row.Field(Of String)("Value3")
row("Value3") = String.Format("{0}-{1}-{2}W",
tmp.Substring(0, 3),
tmp.Substring(3, 2),
tmp.Substring(5, 4))
Next row
The tmp var is just to shorten the code.
I'm working with the following bit of code in VisualBasic.NET. It's essentially supposed to be pulling a row ID from the table with specific conditions in mind. However, I would like to set up a failsafe of getting around those conditions if need be.
I'm trying to write an If statement to compare the Item(0) against but this bit of code seems to trigger no matter what. How can I compare to see if the Query being written as QuestionConnectionQuery is actually returning rows?
For i As Integer = 1 To intNoOfQuestions
'TODO: If there are no valid questions, pull up any of them that meets the difficulty requirement....
' Go into the Database and retrieve a question that hasn't been selected in the last seven days.
Dim QuestionConnectionQuery As New OleDb.OleDbCommand("SELECT TOP 1 Questions.QuestionID, Questions.QuestionCategory & ' : ' & Questions.QuestionSubCategory AS Category FROM Questions WHERE (((Questions.QuestionDifficulty)=[?])) OR (((Questions.LastDateRevealed) Is Null)) OR ((Questions.LastDateRevealed)>=DateAdd('d',-7,Now())) ORDER BY Rnd(QuestionID);", QuestionConnection)
QuestionConnectionQuery.Parameters.AddWithValue("?", intQuestionDifficulty(i - 1).ToString)
Dim QuestionDataAdapter As New OleDb.OleDbDataAdapter(QuestionConnectionQuery)
Dim QuestionDataSet As New DataSet
QuestionDataAdapter.Fill(QuestionDataSet, "Questions")
' If the result is not null... add it to the array.
If IsNothing(QuestionDataSet.Tables("Questions").Rows(0).Item(0)) Then
' Add that to the intQuestArray() array
intQuestArray(i - 1) = QuestionDataSet.Tables("Questions").Rows(0).Item(0)
Else
MessageBox.Show("ERROR: Not enough questions.")
QuestionDataAdapter.Fill(QuestionDataSet, "Questions")
End If
' Update the database by adding today's date to the "LastDateRevealed" column of the table.
Dim QuestionUpdateQuery As New OleDb.OleDbCommand("UPDATE Questions SET LastDateRevealed=NOW() WHERE QuestionID = [?]", QuestionConnection)
QuestionUpdateQuery.Parameters.AddWithValue("?", QuestionDataSet.Tables("Questions").Rows(0).Item(0).ToString)
QuestionUpdateQuery.ExecuteNonQuery()
Next
If IsDBNull(QuestionDataSet.Tables("Questions").Rows(0).Item(0)) Then
https://msdn.microsoft.com/en-us/library/tckcces5(v=vs.90).aspx
See the select below.
dim query = from a in MyContext.MyTables
Where Not a.ID = 1
Select a
I want to check if a value of a field is null. I am doing the following:
if query.count > o then
if a(0)("field") is nothing then
messagebox.show("INVALID VALUE FOR RETURNING")
end if
end if
It is generation an exepction that I can't compare the value a(0)("field").
How should I do it?
Thanks.
For Each dr In ds.Tables(0).Rows
If String.IsNullOrEmpty(dr("BIL")) Then
dr.Delete() //how to delete this row?
End If
Next
first,will loop all data then check which row in BIL column are empty,if the row in BIL column are empty,then delete the row from dataset,how to delete this empty datarow?
Do you want to delete it in your database or do you want to remove it from the DataTable? Btw, use dr.IsNull("BIL") instead. Your code compiles only because you've set OPTION STRICT off because dr("BIL") returns object instead of string.
Dataset are getting data from EXCEL,so,dont have any identity
column.BTW i just want remove from datatable, not database
Then you have to use DataRowCollection.Remove instead of DataRow.Delete. With Delete wthe row will change it's RowState to Deleted. If you then use a DataAdapter to update the DataSet/DataTable or DataRow it will be deleted in the database.
But you can also use Linq-To-DataSet to filter the table and use DataRow.Field extension method which is strongly typed and supports nullable types:
Dim notNullBilRows = From row In ds.Tables(0)
Where Not String.IsNullOrEmpty(row.Field(Of String)("BIL"))
Now you can use CopyToDataTable to create a new DataTable with only rows where BIL is not null, which seems to be the actual requirement.
Dim tblNotNullBilRows = notNullBilRows.CopyToDataTable()
Here's the non-Linq approach with Remove, you have to create an intermediate collection since you cannot remove elements from a collection during enumeration:
Dim removeList = New List(Of DataRow)
For Each dr As DataRow In ds.Tables(0).Rows
If String.IsNullOrEmpty(dr.Field(Of String)("BIL")) Then
removeList.Add(dr)
End If
Next
For Each dr As DataRow In removeList
ds.Tables(0).Rows.Remove(dr)
Next
Try this:
For i As Integer = dt.Rows.Count - 1 To 0 Step -1
If String.IsNullOrEmpty(dt.Rows(i)("BIL")) Then
dt.Rows.RemoveAt(i)
End If
Next
You will want to put the index of the rows you wish to delete into an array, then iterate through the array deleting each rows from the datatable using the indexes. You will not need an 'identity' column to do this, the rows will automatically be asigned indexes.
Assuming you have 2 columns in table tbl: ColumnA and ColumnB
Dim dv as new DataView
dv = new DataView(tbl)
dv.RowFilter = "ColumnA <> '' AND ColumnB <> ''"
tbl = dv.ToTable()
tbl should no longer have empty rows. Hope this helps.
I'm currently pulling information using a query that I'm not allowed to tamper with:
Dim dt As DataTable = BLL.GetData(variable).Tables(0)
Immediately afterwards, I'm removing any records where a field begins with a specific value:
For Each dr As DataRow In dt.Rows
If dr.Item(2).ToString().StartsWith("value") Then
dr.Delete()
End If
Next
What I'd really like to do is something like:
dt.Select.Where(field1 => field1.StartsWith("value")).Delete()
I know that is not the syntax of it and I'm probably very off from what it would be like. The For Each works fine, I'm just trying to "simplify" it. Any idea? Any and all help is appreciated.
Actually, your initial code is probably the cleanest and most straight forward.
To delete items using LINQ, you first need to read them into a separate collection, then loop through that collection and call Delete on each record. If you'd rather go that route, you could try:
Dim records = dt.Rows.Where(Function(r) r.StartsWith("value")).ToList()
For Each r In records
r.Delete()
Next
The answer I think you are looking for is below from Microsoft. https://msdn.microsoft.com/en-us/library/det4aw50(v=vs.110).aspx?cs-save-lang=1&cs-lang=vb#code-snippet-2
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