Isaias Toledo Isaias Toledo - 6 months ago 23
Vb.net Question

How to get values in a column of a DataTable?

I have Login page in my Asp.NET project, what i want basically is get the row of a column of a query that returns the i_idficha, contrasena and the s_nombre. The column called s_nombre will be saved in a variable SESSION. Here's what i have:

Protected Sub btnLogin_Click(sender As Object, e As EventArgs) Handles btnLogin.Click

Threading.Thread.Sleep(2000)
Dim cmd As New SqlCommand("SELECT dbo.USUARIO.i_idficha, dbo.CONTRASENA_USUARIO.s_contrasena, dbo.USUARIO.s_nombre FROM dbo.USUARIO INNER JOIN dbo.CONTRASENA_USUARIO ON dbo.USUARIO.i_idficha = dbo.CONTRASENA_USUARIO.i_ficha WHERE i_idficha = @ficha AND s_contrasena = @pass", cn)
cmd.CommandType = CommandType.Text
cmd.Parameters.AddWithValue("@ficha", SqlDbType.Int).Value = txtUser.Text
cmd.Parameters.AddWithValue("@pass", SqlDbType.VarChar).Value = txtPass.Text
cn.Open()
Dim adp As New SqlDataAdapter(cmd)
Dim table As New DataTable()

adp.Fill(table)
Dim nombre = table.Rows("s_nombre").ToString()
If table.Rows.Count <> 0 Then
If CheckBox1.Checked Then
Response.Cookies("FICHA").Value = txtUser.Text
Response.Cookies("CONTRASENA").Value = txtPass.Text

Response.Cookies("FICHA").Expires = DateTime.Now.AddDays(10)
Response.Cookies("CONTRASENA").Expires = DateTime.Now.AddDays(10)
Else
Response.Cookies("FICHA").Expires = DateTime.Now.AddDays(-1)
Response.Cookies("CONTRASENA").Expires = DateTime.Now.AddDays(-1)
End If

Session("NOMBRE") = nombre
Response.Redirect("~/Default.aspx")
Else
Panel1.Visible = True
End If

End Sub


What i did here was to declare a variable called nombre that is equal to


table.Rows("s_nombre").ToString()


And save it in a variable SESSION("NOMBRE") but doesn't work.

This is the error:


The input string does not have the correct format


This is my code-behind for the Default.aspx:

Protected Sub Page_Load(sender As Object, e As EventArgs) Handles Me.Load
If Session("FICHA") <> Nothing Then
Label1.Text = "Bienvendio <i aria-hidden='true' class='glyphicon glyphicon-user'></i> " & Session("NOMBRE").ToString()
Else
Response.Redirect("~/Login.aspx")
End If
End Sub

Protected Sub linkBtnLogOut_Click(sender As Object, e As EventArgs) Handles linkBtnLogOut.Click
Session("FICHA") = Nothing
Response.Redirect("~/Login.aspx")
End Sub


How to save the column called s_nombre of my query?

Aki Aki
Answer

I'm pretty sure that table.Rows(x) expects the row index, not the column string. So it should be:

Dim nombre = table.Rows(0)("s_nombre").ToString()
Comments