check which item is selected? - vb.net

I try to check which data is selected in a DataGridViewComboBoxCell
Dim status As Double
For x As Integer = 0 To ATCGRID.Rows.Count - 1
If ATCGRID.Rows(x).Cells(2).Value = "Full" Then
status = 1
ElseIf ATCGRID.Rows(x).Cells(2).Value = "Empty" Then
status = 0
ElseIf ATCGRID.Rows(x).Cells(2).Value = "Half" Then
status = 0.5
End If
MessageBox.Show(status)
Next x
But Its getting error
Conversion from string "Full" to type "Double" is not valid.
How can I solve this?

Try to Parse your type database,
Dim strSQL As String = "INSERT INTO ATTENDANCE(EMP_ID,EMP_NAME,AT_DATE,AT_STATUS,AT_REMARK)VALUES(#EMP_ID,#EMP_NAME,#AT_DATE,#AT_STATUS,#AT_REMARK)"
query = New SqlCommand(strSQL, Conn)
query.Parameters.Add("#EMP_ID",SqlDbType.Decimal)
query.Parameters.Add("#EMP_ID").Value=id
query.Parameters.Add("#EMP_NAME",SqlDbType.Varchar,100)' Parse your length
query.Parameters.Add("#EMP_NAME").Value=name
query.Parameters.Add("#AT_DATE",SqlDbType.Date)
query.Parameters.Add("#AT_DATE").Value=atdate
query.Parameters.Add("#AT_STATUS",SqlDbType.Decimal)
query.Parameters.Add("#AT_STATUS").Value=status
query.Parameters.Add("#AT_REMARK",SqlDbType.Varchar,50)
query.Parameters.Add("#AT_REMARK").Value=name

The Value in the cells is a number, so it cannot be compared that way. Try this:
If ATCGRID.Rows(x).Cells(2).Value.ToString() = "FULL" Then

Related

Adding new row to unbound datagridview

I have an unbound datagridview. Because of the various things I am doing with the data in the grid I do not want to bind it. The columns are predefined in the settings (Edit Columns) of the datagridview.
I want to create a new row and then populate the grid row with data. I am trying to use the .Add.Rows method but it is failing with
{"Index was out of range. Must be non-negative and less than the size of the collection." & vbCrLf & "Parameter name: index"}
The following SQL retrieves data:
USE CCAP
declare #ScheduleName as varchar(30) = 'Walk-In Center April Wk 1 2019'
Select ShiftName, ScheduleStart, ScheduleEnd, Position, ADP_ID1,
Name1,ADP_ID2, Name2, ADP_ID3, Name3, ADP_ID4, Name4, ADP_ID5,
Name5, ADP_ID6, Name6, ADP_ID7, Name7
from FormattedSchedules
where ScheduleName = #ScheduleName;
and the rowcount is greater than 0 so it is getting results.
I do not understand what index is out of range or why the collection is 0
Code is below:
Tried .Rows.Add(1) and .Rows.Add() and .Rows.Add("")
Dim FSchedCmd As SqlCommand
Dim FSchedSQL As String
Dim FSchedConn As New SqlConnection()
Dim FSchedadapter As New SqlDataAdapter()
Dim i As Integer = 0
Dim rowIndex As Integer
Dim row As DataGridViewRow
AddedNewRow = 1
Dim dsFSched As New DataSet()
FSchedSQL = "Select ShiftName, ScheduleStart, ScheduleEnd, Position, ADP_ID1, Name1, ADP_ID2, Name2, ADP_ID3, Name3, ADP_ID4, Name4, ADP_ID5, Name5, ADP_ID6, Name6, ADP_ID7, Name7 from FormattedSchedules where ScheduleName = #ScheduleName;"
Try
If GlobalVariables.logProd = 1 Then
GlobalVariables.strConnection = "CCAPProdConnectionString"
Else
GlobalVariables.strConnection = "CCAPTestConnectionString"
End If
FSchedConn.ConnectionString = System.Configuration.ConfigurationManager.ConnectionStrings(GlobalVariables.strConnection).ConnectionString
FSchedConn.Open()
FSchedCmd = New SqlCommand(FSchedSQL, FSchedConn)
FSchedCmd.Parameters.Add("#ScheduleName", SqlDbType.VarChar).Value = cboCreateScheduleName.Text
FSchedadapter.SelectCommand = FSchedCmd
FSchedadapter.Fill(dsFSched)
FSchedadapter.Dispose()
FSchedCmd.Dispose()
FSchedConn.Close()
'dgvCreateSchedule.DataSource = dsFSched.Tables(0)
dgvCreateSchedule.Rows.Clear()
With dgvCreateSchedule
Dim RowNo As Long = 0
'.RowCount = 0
While RowNo <= dsFSched.Tables(0).Rows.Count - 1
.Rows.Add(1)
.Rows(RowNo).Cells(0).Value = dsFSched.Tables(0).Rows(RowNo).Item(0) 'ShiftName
'.Rows(RowNo).Cells(1).Value = dsFSched.Tables(0).Rows(RowNo).Item(1) 'Start Time
.Rows(RowNo).Cells(1).Value = Convert.ToDateTime(dsFSched.Tables(0).Rows(RowNo).Item(1)).TimeOfDay
'.Rows(RowNo).Cells(2).Value = dsFSched.Tables(0).Rows(RowNo).Item(2) 'End Time
.Rows(RowNo).Cells(2).Value = Convert.ToDateTime(dsFSched.Tables(0).Rows(RowNo).Item(2)).TimeOfDay 'End Time
.Rows(RowNo).Cells(3).Value = dsFSched.Tables(0).Rows(RowNo).Item(3) 'Position
.Rows(RowNo).Cells(4).Value = dsFSched.Tables(0).Rows(RowNo).Item(4) 'ADP_ID1
.Rows(RowNo).Cells(5).Value = dsFSched.Tables(0).Rows(RowNo).Item(5) 'Name1
.Rows(RowNo).Cells(6).Value = dsFSched.Tables(0).Rows(RowNo).Item(6) 'ADP_ID2
.Rows(RowNo).Cells(7).Value = dsFSched.Tables(0).Rows(RowNo).Item(7) 'Name2
.Rows(RowNo).Cells(8).Value = dsFSched.Tables(0).Rows(RowNo).Item(8) 'ADP_ID3
.Rows(RowNo).Cells(9).Value = dsFSched.Tables(0).Rows(RowNo).Item(9) 'Name3
.Rows(RowNo).Cells(10).Value = dsFSched.Tables(0).Rows(RowNo).Item(10) 'ADP_ID4
.Rows(RowNo).Cells(11).Value = dsFSched.Tables(0).Rows(RowNo).Item(11) 'Name4
.Rows(RowNo).Cells(12).Value = dsFSched.Tables(0).Rows(RowNo).Item(12) 'ADP_ID5
.Rows(RowNo).Cells(13).Value = dsFSched.Tables(0).Rows(RowNo).Item(13) 'Name5
.Rows(RowNo).Cells(14).Value = dsFSched.Tables(0).Rows(RowNo).Item(14) 'ADP_ID6
.Rows(RowNo).Cells(15).Value = dsFSched.Tables(0).Rows(RowNo).Item(15) 'Name6
.Rows(RowNo).Cells(16).Value = dsFSched.Tables(0).Rows(RowNo).Item(16) 'ADP_ID7
.Rows(RowNo).Cells(17).Value = dsFSched.Tables(0).Rows(RowNo).Item(17) 'Name7
RowNo = RowNo + 1
End While
End With
If dgvCreateSchedule.RowCount > 0 Then
dgvCreateSchedule.Rows(0).Selected = True
dgvCreateSchedule.CurrentCell = dgvCreateSchedule.Rows(0).Cells(0)
'dgvCreateSchedule.FirstDisplayedScrollingRowIndex = dgvCreateSchedule.CurrentRow.Index
End If
Catch ex As Exception
MessageBox.Show("Cannot open FormattedSchedules to load grid")
End Try
AddedNewRow = 0
Error message from line: .Rows.Add(1)
Index was out of range. Must be non-negative and less than the size of the collection." & vbCrLf & "Parameter name: index
This should be the fastest option:
dgvCreateSchedule.Rows.Clear()
For Each xrow As DataRow In TempDataTable.dsFSched.Tables(0).Rows
dgvCreateSchedule.Rows.Add(xrow.ItemArray)
Next
What it does adds all "Cells" along with row.
And when editing cells, I prefer to use
dgvCreateSchedule(y,x).Value = somevalue
'Though it's a little bit strange, as it's column first then row for location hence y then x axis , opposed to usual row then column thats x then y axis
Add it like this, assuming there is the same column count/order
.Rows.Add(dsFSched.Tables(0).Rows(RowNo).ItemArray)
I changed the name of the DGV to DataGridView1 because that is what I happened to have in my test project.
You can use conditional compile statements to chose the correct connection string. Not necessary to keep a Boolean variable somewhere to determine correct string. I know I would forget to change it for the release version.
You did a good job closing and disposing of database objects but if there is an error all that good work will be for naught. A Using...End Using block will accomplish the close, dispose even if there is an error.
Pass the connection string directly to the constructor of the connection and pass the Sql statement and the connection directly to the constructor of the command.
Don't open your connection until the last minute. In the case of a DataAdapter.Fill, the connection is opened and closed for you however, if the adapter finds and open connection it leaves it open. In this case there is no need for an adapter or a DataSet.
I do not see anything wrong with your line .Rows.Add(1). The problem comes on the next line. The index of DataGridView.Rows is an Int32, Integer in vb.net, and you have declared RowNo as Long. Of course you will want to use the code suggested by #CruleD answer.
Private Sub OPCode()
Dim dt As New DataTable
Dim FSchedSQL = "Select ShiftName, ScheduleStart, ScheduleEnd, Position, ADP_ID1, Name1, ADP_ID2, Name2, ADP_ID3, Name3, ADP_ID4, Name4, ADP_ID5, Name5, ADP_ID6, Name6, ADP_ID7, Name7 from FormattedSchedules where ScheduleName = #ScheduleName;"
Try
#If Not DEBUG Then
GlobalVariables.strConnection = "CCAPProdConnectionString"
#Else
GlobalVariables.strConnection = "CCAPTestConnectionString"
#End If
Using FSchedConn As New SqlConnection(ConfigurationManager.ConnectionStrings(GlobalVariables.strConnection).ConnectionString)
Using FSchedCmd As New SqlCommand(FSchedSQL, FSchedConn)
FSchedCmd.Parameters.Add("#ScheduleName", SqlDbType.VarChar).Value = cboCreateScheduleName.Text
FSchedConn.Open()
dt.Load(FSchedCmd.ExecuteReader)
End Using
End Using
DataGridView1.Rows.Clear()
For Each xrow As DataRow In dt.Rows
DataGridView1.Rows.Add(xrow.ItemArray)
Next
If DataGridView1.RowCount > 0 Then
DataGridView1.Rows(0).Selected = True
DataGridView1.CurrentCell = DataGridView1.Rows(0).Cells(0)
End If
Catch ex As Exception
MessageBox.Show("Error loading grid")
End Try
End Sub

converting dataset.Compute("Sum(TARGET_AREA)", "") to .toString("N")

I am trying to convert my computed database columns in my datagrid. I was able to compute the columns and wanted to fix the format of the results.
Label18.Text = dataset.Compute("Sum(TARGET_AREA)", "") & " (ha)"
An example of my output is 100000.00 (ha)
What I wanted for my output is to look like this 100,000.00 (ha)
I tried using .toString("N") but no luck.
my column type is Decimal and the others were Double.
Any idea on how to fix it?
You could use String.Format method.
Example
value = 1234.567890
Console.WriteLine(value.ToString("0,0.00", CultureInfo.InvariantCulture))
Source: MSDN Custom Numeric Format Strings.
Here is an example using a DataTable - Note that you may want to check the sum if the column allows nulls. Also, the sum here is invoked over the datatable object not the dataset (as in your question) - This code has been automatically translated from C# - I assume it syntactically OK.
Dim dataset As New DataSet("ds1")
Dim dt As New DataTable("dt")
Dim dc As DataColumn = dt.Columns.Add("TARGET_AREA", GetType(System.Decimal))
Dim dr As DataRow = dt.Rows.Add()
dr("TARGET_AREA") = 100000.0
Dim finalResult As String = ""
Dim value As Decimal
If dt.Rows.Count > 0 Then
Dim result_obj As Object = dt.Compute("Sum(TARGET_AREA)", "")
If result_obj Is System.DBNull.Value Then
value = 0
Else
value = Convert.ToDecimal(result_obj)
End If
finalResult = String.Format(value.ToString("0,0.00", System.Globalization.CultureInfo.InvariantCulture)) & " (ha)"
Console.WriteLine(finalResult)
End If
Console.Read()
Return

mongodb query to find field - vb.net

How would I structure a query for mongodB to make a 'stored procedure' or make the request to select an id which is marked active and then delete that field immediately or mark it as inactive; whichever one has the better performance. Here is the collection structure:
db = server.GetDatabase("test")
siteCollection = db("test")
collection = db.GetCollection(Of BsonDocument)("siteids")
Dim book As BsonDocument = New BsonDocument() _
.Add("siteid", BsonValue.Create(BsonType.String)) _
.Add("active", BsonValue.Create(BsonType.String))
collection.Insert(book)
I found the java version and not sure if this will work and what is .net syntax
db.things.find( { x : 4 } , { j : 1 } )
This apparantly finds records where x = 4 but only return where j = 1 so I want one siteid where active = 'N'
Thanks; here is what I have come up with thus far:
' Dim squery = Query.EQ("active", "Y")
Dim squery = Query.EQ("active", "Y")
Dim ssort = SortBy.Null
Dim uupdate = Update.[Set]("active", "N")
Dim result = collection.FindAndModify(squery, ssort, uupdate)
' Dim dresult = collection.FindAs(Of BsonDocument)(squery)
Dim newSiteId As String = dresult.Count
As you can see the first line commented out I thought a simple select would be implemented but that comes back null. Then with the second last statement commented out that too returned value Null.

Insert a Date as a String to Access using a DAO Recordset

I am using some code I found in an old C# post to run a DAO insert into Access with VB.net. I ran the code to insert numbers and it ran fine. However When i try to insert a date as a string between hashes I get a Data type conversion error. I have had a look and I can't see how to change the data type of the recordset field to accept a string/date.
Here is the code:
Dim dbEngine As New dao.DBEngine
Dim db As dao.Database = dbEngine.OpenDatabase(DataDirectoryName & DatabaseName)
Dim rs As dao.Recordset = db.OpenRecordset(TableName)
Dim myFields As dao.Field() = New dao.Field(FieldNames.Count - 1) {}
For k As Integer = 0 To FieldNames.Count - 1
myFields(k) = rs.Fields(FieldNames(k))
Next
dbEngine.BeginTrans()
For i As Double = 0 To Data.Rows - 1
rs.AddNew()
For k As Integer = 0 To FieldNames.Count - 1
rs.Fields(k).Value = Data.Value(k, i)
rs.Fields(FieldNames(k)).Value = Data.Value(k, i)
myFields(k).Value = Data.Value(k, i)
Next
rs.Update()
Next
dbEngine.CommitTrans()
rs.Close()
db.Close()
Here is one row of data:
(0) = "74"
(1) = "#01 February 2012 00:02:00#"
(2) = "40"
(3) = "130"
(4) = "60"
'Data' is a custom class that is a list (of list (of string)).
While VBA will accept date delimiters on your string, eg #11 February 2013 20:23:11# it seems that VB.Net will not, however, it does accept for an MS Access update.
rs.Fields("adate").Value = CDate("11 February 2013 20:23:11")

coversion from string ""to double type is invalid

iam passing a textbox value(the value is 10:1:1) into a string and when iam running the application iam getting the following error "coversion from string "10:1:1" to double type is invalid". kindly find the code below and help me on the same: (also the textbox values should be greater than 0 always)
Dim strEncrypt As String = txtData.Text
If strEncrypt > 0 Then // I am getting the error here
txtEncryptedData.Text = Encrypt(strEncrypt)
Else
MessageBox.Show(
"Enter the Value greater then 0:")
End If
Thanks,
Rams
I believe you want this...
If strEncrypt.Length > 0 Then
Maybe you want:
Function Check(ByVal s As String) As Boolean
Dim parts As String()
parts = s.Split(":")
If parts.Length = 0 Then
Check = False
Else
Check = True
For Each sval As String In parts
Check = Check And Int32.Parse(sval) > 0
Next
End If
End Function
so you can use it like Check(txtData.Text).