User665608656 posted
Hi mjta,
According to your code,the issue is that when you execute
Response.Write Session(sessionUserID)
, the Session("sessionUserID") variable is not defined.
You need to confirm whether there is a case where reader1(1) = str is satisfied in the while loop, and if there is no case where reader1(1) = str is satisfied, then
Session.Add("sessionUserId", reader1(0).ToString)
is not executed which led to subsequent errors.
In addition, I found that when you execute this statement
Response.Write Session(sessionUserID)
, there are some issues with your grammar. You need to add double quotation marks to the sessionUserID.
I have made a similar example , you could refer to it:
The result of this work demo:
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" DataKeyNames="EmplId" OnSelectedIndexChanged="GridView1_SelectedIndexChanged1" >
<Columns>
<asp:BoundField DataField="EmplId" HeaderText="EmplId" ReadOnly="True" SortExpression="EmplId" />
<asp:BoundField DataField="FirstName" HeaderText="FirstName" SortExpression="FirstName" />
<asp:BoundField DataField="LastName" HeaderText="LastName" SortExpression="LastName" />
<asp:BoundField DataField="EmailAddr" HeaderText="EmailAddr" SortExpression="EmailAddr" />
<asp:CommandField ShowSelectButton="True" SelectText="Select" />
</Columns>
<SelectedRowStyle BackColor="LightCyan"
ForeColor="DarkBlue"
Font-Bold="true" />
</asp:GridView>
code behind:
Protected Sub GridView1_SelectedIndexChanged1(ByVal sender As Object, ByVal e As EventArgs)
Dim str As String = GridView1.SelectedRow.Cells(1).Text
Dim ConnectionString As String = ConfigurationManager.ConnectionStrings("ConnectionString").ConnectionString
Dim checkSql1 As String = "select* from Employee WHERE Employee.FirstName = @FirstName"
Using myconnection As SqlConnection = New SqlConnection(ConnectionString)
Dim command1 As SqlCommand = New SqlCommand(checkSql1, myconnection)
myconnection.Open()
command1.Parameters.AddWithValue("@FirstName", str)
Dim reader1 As SqlDataReader = command1.ExecuteReader()
Try
While (reader1.Read())
If reader1(1).ToString() = str Then Session.Add("sessionUserId", reader1(0).ToString())
End While
Catch ex As Exception
Response.Write(ex.Message)
Finally
reader1.Close()
End Try
myconnection.Close()
End Using
If Session("sessionUserID") IsNot Nothing Then
Response.Write(Session("sessionUserID"))
End If
End Sub
The result of this work demo:

Best Regards,
YongQing.