Question: I have 1 DataGridView with 3 columns, 1 button named as **AssignID**, 1 Database with **EmployeeList** Table.

Columns of Datagridview

1. Column 1 = EmployeeID
2. Column 2 = EmployeeName
3. Column 3 = Department

I'm pasting the data of **EmployeeName** and **Department** from excel into DataGridView leaving column 1 as blank. My problem is how to automatically assign the **EmployeeID** per Employee in the DataGridView when I press the button **AssignID**. The last **IDNumber** in the database is 10000.

Appreciate your help. Im still learning vb.net. Thanks in Advance.

Im using below code:

```
Private Sub AssignID_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles AssignID.Click
    Dim Dbcon As New OleDbConnection(connStr)

    Dbcon.Open()

    Dim query As String
    Dim dbup As New OleDbCommand
    Try

        query = "SELECT Max (EmployeeID) from EmployeeList"
        dbup = New OleDbCommand(query, Dbcon)

        Dim EmpID As Integer

        EmpID = dbup.ExecuteScalar

        Dim i2 As Integer
        i2 = Me.NewEmployeesDataGridview.CurrentRow.Index

        NewEmployeesDataGridview.Item(0, i2).Value() = EmpID

        For x As Integer = 0 To NewEmployeesDataGridview.Rows.Count - 2
            NewEmployeesDataGridview.Rows(x).Cells(0).Value = NewEmployeesDataGridview.Rows(0).Cells(0).Value + 1

        Next

        NewEmployeesDataGridview.AllowUserToAddRows = False

    Catch ex As Exception
        MsgBox(ex.Message)
    End Try

End Sub

```

Answer: 
First thing first: a cast of an `object` to `bool` is valid only when the `object` is a reference type wrapper for the `bool` or `Nullable<bool>` type:

```
bool val1 = true;
object mydata1=val1;
if ((bool) val1) { ... } // This is valid
bool? val2 = false;
object mydata2=val2;
if ((bool) val2) { ... } // This is valid too

```

When you cast an `object` to another type in C#, the runtime has enough information about the runtime type of the object being typecast to validate the operation, and throw an `InvalidCastException` when the cast is invalid.

In situations when the dynamic type of the object at runtime does not match the type to which you would like it to cast, you should use methods of the [`Convert`](http://msdn.microsoft.com/en-us/library/system.convert%28v=vs.110%29.aspx) class.
Probably your best course of action to reduce exceptions and make casting easy is to use the [as](http://msdn.microsoft.com/en-us/library/cscsdfbt.aspx) operator and a [nullable](http://msdn.microsoft.com/en-us/library/b3h38hb0(v=vs.110).aspx) boolean `bool?`.

```
object test1 = 1;
object test2 = true;

var testBool1 = test1 as bool?;
var testBool2 = test2 as bool?;

if (testBool1.HasValue) 
{
  // test1 is a boolean
  bool mybool = testBool1.Value;
}

if (testBool2.HasValue)
{
  // test2 is a boolean
  bool mybool = testBool2.Value;
}

```