Hi, I'm using asp.net together with vb.net. I am trying to develop:
1. a login page in asp.net, once user enter the correct username and password, this will be directed to the User page.
2. In User page, there will be some text fields of the user (eg. name and address), all these suppose to retrieve from SQL Server. In here, if the username is found in the database, his/her data will be displayed in the textboxes ( eg. name and address), if not, the textboxes remain empty. User can choose to edit or enter new data into the textboxes and submit back to the datadase.
3. Once updated, user can click "save and logout" to save the data and logout.
I've done the login part, but only in (2), I can't retrieve the user's data from databases based on User.Identity.Name. Any idea how to retrieve data based on user's username?
Thanks.

What error messages/symptoms are you getting? Post code from where you think problem might be happening. If you want help with your homework, you are going to have to give us some details

The scenario:
At Login.aspx, user will enter username and password to login, this works perfectly, authenticating against database in SQL Server.

Here's the code:
Login.aspx

<%@ Page Language="vb" AutoEventWireup="false" Codebehind="Login.aspx.vb" Inherits="LoginTest.Login"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<HTML>
	<HEAD>
		<title>Login - Login Test</title>
		<meta name="GENERATOR" content="Microsoft Visual Studio.NET 7.0">
		<meta name="CODE_LANGUAGE" content="Visual Basic 7.0">
		<meta name="vs_defaultClientScript" content="JavaScript">
		<meta name="vs_targetSchema" content="http://schemas.microsoft.com/intellisense/ie5">
	</HEAD>
	<body>
		<form Runat="Server" ID="Form1">
			<h2>Please Login:</h2>
			<asp:Label ID="lblMessage" ForeColor="Red" Font-Bold="True" Runat="Server" />
			<p>
				<b>Username:</b>
				<br>
				<asp:TextBox ID="txtUsername" Runat="Server" />
				<asp:RequiredFieldValidator ControlToValidate="txtUsername" Text="Required!" Runat="Server" ID="Requiredfieldvalidator1" />
			<p>
				<b>Password:</b>
				<br>
				<asp:TextBox ID="txtPassword" Runat="Server" TextMode="Password" />
				<asp:RequiredFieldValidator ControlToValidate="txtPassword" Text="Required!" Runat="Server" ID="Requiredfieldvalidator2" />
			<p>
				<asp:Button Text="Login!" OnClick="Button_Click" Runat="Server" ID="Button1" />
				<hr>
		</form>
	</body>
</HTML>

Login.aspx.vb

Imports System
Imports System.IO
Imports System.Web
Imports System.Data.SqlClient
Imports System.Collections
Imports System.Web.Security

Public Class Login
    Inherits System.Web.UI.Page
    Protected WithEvents lblMessage As System.Web.UI.WebControls.Label
    Protected WithEvents txtUsername As System.Web.UI.WebControls.TextBox
    Protected WithEvents Requiredfieldvalidator1 As System.Web.UI.WebControls.RequiredFieldValidator
    Protected WithEvents txtPassword As System.Web.UI.WebControls.TextBox
    Protected WithEvents Requiredfieldvalidator2 As System.Web.UI.WebControls.RequiredFieldValidator
    Protected WithEvents Button1 As System.Web.UI.WebControls.Button

#Region " Web Form Designer Generated Code "

    'This call is required by the Web Form Designer.
    <System.Diagnostics.DebuggerStepThrough()> Private Sub InitializeComponent()

    End Sub

    Private Sub Page_Init(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Init
        'CODEGEN: This method call is required by the Web Form Designer
        'Do not modify it using the code editor.
        InitializeComponent()
    End Sub

#End Region

    Private Sub Page_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
        'Put user code to initialize the page here
        Dim strLinkPath As String

        If Not IsPostBack Then
            strLinkPath = String.Format("Register.aspx?ReturnUrl={0}", _
              Request.Params("ReturnUrl"))
            'lnkRegister.NavigateUrl = String.Format(strLinkPath)
        End If
    End Sub

    Sub Button_Click(ByVal s As Object, ByVal e As EventArgs)

        If IsValid Then
            If DBAuthenticate(txtUsername.Text, txtPassword.Text) > 0 Then
                FormsAuthentication.RedirectFromLoginPage(txtUsername.Text, False)
                Response.Redirect("Success.aspx")
            End If
        End If
    End Sub

    Function DBAuthenticate(ByVal strUsername As String, ByVal strPassword As String) As Integer
        Dim conMyData As SqlConnection
        Dim cmdSelect As SqlCommand
        Dim parmReturnValue As SqlParameter
        Dim intResult As Integer


        conMyData = New SqlConnection(ConfigurationSettings.AppSettings("connectionstring"))
        cmdSelect = New SqlCommand("DBAuthenticate", conMyData)
        cmdSelect.CommandType = CommandType.StoredProcedure
        parmReturnValue = cmdSelect.Parameters.Add("RETURN_VALUE", SqlDbType.Int)
        parmReturnValue.Direction = ParameterDirection.ReturnValue
        cmdSelect.Parameters.Add("@username", strUsername)
        cmdSelect.Parameters.Add("@password", strPassword)
        conMyData.Open()
        cmdSelect.ExecuteNonQuery()
        intResult = cmdSelect.Parameters("RETURN_VALUE").Value
        conMyData.Close()
        If intResult < 0 Then
            If intResult = -1 Then
                lblMessage.Text = "Username Not Registered!"
            Else
                lblMessage.Text = "Invalid Password!"
            End If
        End If
        Return intResult
    End Function

End Class

Once successfully logged in, user will be directed to this page "Success.aspx", and the page should be able to retrieve the user's details from the database, in this case the password of the user is to be displayed. However, my program can't retrieve and display the user's password in the textbox/label. Note: connectionstring is stored in web.config.
Some of the SQL is stored in the stored procedures.

Successful.aspx

<%@ Page Language="vb" AutoEventWireup="false" Codebehind="Success.aspx.vb" Inherits="LoginTest.Success"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<HTML>
	<HEAD>
		<title>Success</title>
		<meta content="Microsoft Visual Studio.NET 7.0" name="GENERATOR">
		<meta content="Visual Basic 7.0" name="CODE_LANGUAGE">
		<meta content="JavaScript" name="vs_defaultClientScript">
		<meta content="http://schemas.microsoft.com/intellisense/ie5" name="vs_targetSchema">
	</HEAD>
	<body>
		<asp:label id="NameLabel" Runat="server"></asp:label><asp:label id="FormResponse" Runat="server"></asp:label>
		<form id="formSuccess" method="post" runat="server">
			<h1>Welcome
				<%=User.Identity.Name%>
			</h1>
			<br>
			You have successfully logged in to the secure page.
			<br>
			Username:<%=User.Identity.Name%>
			<br>
			<br>
			Password:
			<asp:Label id="txtPassword" Runat="server" name="password"></asp:Label><br>
			<asp:button id="btnSubmit" Runat="server" Text="Submit"></asp:button>
			<asp:button id="btnLogout" Runat="server" Text="Logout"></asp:button></form>
	</body>
</HTML>

Success.aspx.vb

Imports System
Imports System.IO
Imports System.Web
Imports System.Data.SqlClient
Imports System.Collections
Imports System.Web.Security
Imports System.Data
Imports System.Data.SqlDbType
Imports System.Security.Cryptography
Imports System.Text


Public Class Success
    Inherits System.Web.UI.Page
    Protected WithEvents formSuccess As System.Web.UI.HtmlControls.HtmlForm
    Protected WithEvents txtPassword As System.Web.UI.WebControls.Label
    Protected WithEvents lblmessage As System.Web.UI.WebControls.Label
    Protected WithEvents btnSubmit As System.Web.UI.WebControls.Button
    Protected WithEvents NameLabel As System.Web.UI.WebControls.Label
    Protected WithEvents FormResponse As System.Web.UI.WebControls.Label
    Protected WithEvents btnLogout As System.Web.UI.WebControls.Button
    Protected WithEvents txtUsername As System.Web.UI.WebControls.Label

#Region " Web Form Designer Generated Code "

    'This call is required by the Web Form Designer.
    <System.Diagnostics.DebuggerStepThrough()> Private Sub InitializeComponent()

    End Sub

    Private Sub Page_Init(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Init
        'CODEGEN: This method call is required by the Web Form Designer
        'Do not modify it using the code editor.
        InitializeComponent()
    End Sub

#End Region

    Private Sub Page_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
        'Put user code to initialize the page here

        If Not (User.Identity.IsAuthenticated) Then
            Response.Redirect("Login.aspx")
        End If

        'txtPassword.Text = Profile.password

        If Not Page.IsPostBack Then
            Dim db As UsersDB = New UsersDB("connectionstring")
            txtPassword.Text = db.GetPassword(Page.User.Identity.Name)
        End If

    End Sub

    Public Function GetPassword(ByVal username As String) As String
        'Retrieve the connection string from the configuration file.
        Dim con As SqlConnection = New SqlConnection(ConfigurationSettings.AppSettings("connectionstring"))

        Dim htmlStr As New StringBuilder()

        'Create a parameterized command with placeholders.
        Dim SQL As String = "SELECT * FROM tblUser WHERE username = @username"
        Dim cmd As SqlCommand = New SqlCommand(SQL, con)
        cmd.Parameters.Add("@username", username)
        Dim encryptedData() As Byte
        Try
            'Update the record
            con.Open()
            Dim reader As SqlDataReader = cmd.ExecuteReader()
            If reader.Read() Then
                encryptedData = CType(reader("tblUser"), Byte())
                txtPassword.Text = reader.Item("password")

            End If
            reader.Close()
        Catch
            Return Nothing
        Finally
            con.Close()
        End Try

        'Decrypt and return the password.
        Return EncryptionUtil.DecryptToString(encryptedData, CType(HttpContext.Current.Application("Key"), Rijndael))

    End Function



    Private Sub btnSubmit_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnSubmit.Click

        Dim conMaster As SqlConnection
        Dim cmdInsert As SqlCommand
        Dim intUpdate As Integer
        Dim paramValue As SqlParameter
        'Dim intDate As DateTime = DateTime.Now()

        conMaster = New SqlConnection(ConfigurationSettings.AppSettings("connectionstring"))
        cmdInsert = New SqlCommand("AddData", conMaster)
        cmdInsert.CommandType = CommandType.StoredProcedure

        'Make sure return value is taken from stored procedure
        paramValue = cmdInsert.Parameters.Add("ReturnValue", SqlDbType.Int)
        paramValue.Direction = ParameterDirection.ReturnValue


        'DateAddedLabel.Text = DateTime.Now.ToString


        'Parameters built to eliminate sql injection attacks
        'cmdInsert.Parameters.Add("@date_added", DateTime.Parse(DateAddedLabel.Text))
        'cmdInsert.Parameters.Add("@username", txtUsername.Text)
        cmdInsert.Parameters.Add("@password", txtPassword.Text)



        'Open database connection
        conMaster.Open()

        'Update database by inserting new parameters
        cmdInsert.ExecuteNonQuery()

        If cmdInsert.Parameters("ReturnValue").Value = 1 Then
            'Duplicate value found go to error page
            Response.Redirect("FormError.aspx")
        End If

        'Close database connection
        conMaster.Close()



    End Sub

    Private Sub btnLogout_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnLogout.Click
        FormsAuthentication.SignOut()
        Response.Redirect("Logout.aspx")
    End Sub
End Class

UsersDB.vb

Imports Microsoft.VisualBasic
Imports System
Imports System.Data.SqlClient
Imports System.Data
Imports System.Configuration
Imports System.Web.Security
Imports System.Collections
Imports System.Web
Imports System.Security.Cryptography

Public Class UsersDB
    Protected WithEvents txtUsername As System.Web.UI.WebControls.TextBox

    Private connectionSetting As String

    Public Sub New(ByVal connectionStringSettingName As String)
        Me.connectionSetting = connectionStringSettingName
    End Sub

    Public Function GetPassword(ByVal userName As String) As String
        ' Retrieve the connection string from the configuration file.				
        Dim con As SqlConnection = New SqlConnection(ConfigurationSettings.AppSettings(connectionSetting))

        ' Create a parameterized command with placeholders.
        Dim SQL As String = "SELECT * FROM tblUser " + "WHERE username = @username"
        Dim cmd As SqlCommand = New SqlCommand(SQL, con)
        cmd.Parameters.Add("@username", userName)

        Dim encryptedData As Byte()
        Try
            ' Update the record.
            con.Open()
            Dim reader As SqlDataReader = cmd.ExecuteReader(CommandBehavior.SingleRow)
            reader.Read()
            encryptedData = CType(reader("tblUser"), Byte())
            reader.Close()
        Catch
            Return Nothing
        Finally
            con.Close()
        End Try

        ' Decrypt and return the credit card number.
        Return EncryptionUtil.DecryptToString(encryptedData, CType(HttpContext.Current.Application("Key"), Rijndael))
    End Function


End Class

EncryptionUtil.vb

Imports Microsoft.VisualBasic
Imports System
Imports System.Security.Cryptography
Imports System.IO


Public Class EncryptionUtil
    Inherits System.Web.UI.Page

    Public Shared Function EncryptString(ByVal stringToEncrypt As String, ByVal crypt As SymmetricAlgorithm) As Byte()
        ' Create a cryptographic stream for encryption.
        Dim ms As MemoryStream = New MemoryStream()
        Dim cs As CryptoStream = New CryptoStream(ms, crypt.CreateEncryptor(), CryptoStreamMode.Write)

        ' Write the string to binary data with the help of a BinaryWriter.
        Dim w As BinaryWriter = New BinaryWriter(cs)
        w.Write(stringToEncrypt)
        w.Flush()

        ' All the data has been written. Now, make sure the last block
        ' is properly padded. Failing to do this will cause an error
        ' when you attempt to decrypt the data.
        cs.FlushFinalBlock()

        ' Now move the encrypted data out of the stream,
        ' and into an array of bytes.
        Return ms.ToArray()
    End Function

    Public Shared Function DecryptToString(ByVal dataToDecrypt As Byte(), ByVal crypt As SymmetricAlgorithm) As String
        ' Create a cryptographic stream for decryption.
        Dim ms As MemoryStream = New MemoryStream()
        Dim cs As CryptoStream = New CryptoStream(ms, crypt.CreateDecryptor(), CryptoStreamMode.Write)

        ' Write the binary data to the memory stream.
        cs.Write(dataToDecrypt, 0, dataToDecrypt.Length)
        cs.FlushFinalBlock()

        ' Read the unencrypted data from the stream into a string,
        ' with the help of the BinaryReader.
        Dim r As BinaryReader = New BinaryReader(ms)
        ms.Position = 0
        Dim decryptedData As String = r.ReadString()
        r.Close()

        Return decryptedData
    End Function

End Class

As from above, encryption is not necessary, as I will eventually replace the data to be displayed as normal data, instead of displaying the password.

Need help in retrieving the user's data from database and display on the form, user can edit and update and resubmit back to the database.

i want to store the passwords,who tried possible passwords for already created users

1. well you can directly connect that page2 textboxes to the datatbase using datareader so that value of the textboxes come from the database on the page_load.

2. Else you can use a simple querystring where you can add value of that textboxes by declaring a string on the Response.Redirect method after the page you need to display on page1. Talking about page2 you can call that value using Request.Querystring method.

if you need me to elaborate i can give you the example but try the above methods. good luck

using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using System.Data.SqlClient;

public partial class UpdateProfile : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {

        if (!IsPostBack)
        {
            FillGridWithPatient();
            divPatientUpdate.Visible = false;
        }
    }

    private void FillGridWithPatient()
    {
        SqlConnection conn = null;
        SqlCommand cmd = null;
        SqlDataAdapter da = null;
        DataSet dsPatient = new DataSet();
        try
        {
            conn = new SqlConnection(ConfigurationManager.ConnectionStrings["PConnStr"].ConnectionString);
            conn.Open();
            string sql = "Select * from Patient";
            cmd = new SqlCommand(sql, conn);
            da.Fill(dsPatient);
        }
        catch (Exception ex)
        { }
        finally
        {
            if (conn.State == ConnectionState.Open)
            {
                conn.Close();
            }
        }
    }

    protected void btnCancel_Click(object sender, EventArgs e)
    {

    }

    protected void btnViewProfile_Click(object sender, EventArgs e)
    {
        divPatientUpdate.Visible = true;
        GetSinglePatient(p_id);
    }
    protected void btnEdit_Click(object sender, EventArgs e)
    {

        if (btnEdit.Text == "Edit")
        {
            InsertData();
            btnEdit.Text = "Save";

        }
        else
        {
            UpdateData();
        }
    }

    private void GetSinglePatient()
    {
        SqlConnection conn = null;
        SqlCommand cmd = null;
        SqlDataReader dr=null;
        int p_id = Convert.ToInt32();
        try
        {
            conn = new SqlConnection(ConfigurationManager.ConnectionStrings["PConnStr"].ConnectionString);
            conn.Open();
            string sql = "select * from Patient where P_id=" + p_id;
            cmd = new SqlCommand(sql, conn);
            while (dr.Read())
            {
                txtAge.Text = dr["Age"].ToString();
                txtFirstName.Text = dr["P_FName"].ToString();
                txtLastName.Text = dr["P_LName"].ToString();
                txtZip.Text = dr[" Zip"].ToString();
                txtContactNo.Text = dr["ContactNo"].ToString();
                cmbCity.Text = dr["City"].ToString();
                cmbState.Text = dr["State"].ToString();
                txtEmail.Text = dr["Email_id"].ToString();
            }
        }
        catch (Exception ex)
        {
            Label1.Text = ex.ToString();
            Label1.Visible = true;
        }
        finally
        {
            if (conn.State == ConnectionState.Open)
            {
                conn.Close();
            }
        }


    }

    private void UpdateData()
    {
        SqlConnection conn = null;
        SqlCommand cmd = null;
        try
        {
            conn = new SqlConnection(ConfigurationManager.ConnectionStrings["PConnStr"].ConnectionString);
            string sql = "Update Patient set P_FName=@fname,P_LName=@lname,Age=@age, State=@state ,City=@city ,Email_id=@email ,Sex=@sex ,ContactNo=@contactno Zip=@zip where P_id=@p_id";
            conn.Open();
            cmd = new SqlCommand(sql, conn);
            cmd.Parameters.AddWithValue("@fname", txtFirstName.Text);
            cmd.Parameters.AddWithValue("@lname", txtLastName.Text);
            cmd.Parameters.AddWithValue("@age", txtAge.Text);
            cmd.Parameters.AddWithValue("@state", cmbState.Text);
            cmd.Parameters.AddWithValue("@city", cmbCity.Text);
            cmd.Parameters.AddWithValue("@email", txtEmail.Text);
            if (rbtnFemale.Checked)
            {
                cmd.Parameters.AddWithValue("@sex", rbtnFemale.Text);
            }
            else
            {
                cmd.Parameters.AddWithValue("@sex", rbtnMale.Text);
            }
            cmd.Parameters.AddWithValue("@contactno", txtContactNo.Text);
            cmd.Parameters.AddWithValue("@p_id", Convert.ToInt32(ViewState["P_id"].ToString()));
            cmd.ExecuteNonQuery();
            FillGridWithPatient();
        }

        catch (Exception ex)
        {

            Label1.Text = ex.ToString();
            Label1.Visible = true;
        }
        finally
        {
            if (conn.State == ConnectionState.Open)
            {
                conn.Close();
            }
        }

    }

    private void InsertData()
    {
        SqlConnection conn = null;
        SqlCommand cmd = null;
        try
        {
            conn = new SqlConnection(ConfigurationManager.ConnectionStrings["PConnStr"].ConnectionString);
            string sql = "insert into Patient ( P_FName,P_LName,Age, State ,City ,Email_id,Sex,ContactNo)values(@fname,@lname,@age,@state,@city,@email,@sex,@contactno)";
            conn.Open();
            cmd = new SqlCommand(sql, conn);
            cmd.Parameters.AddWithValue("@fname", txtFirstName.Text);
            cmd.Parameters.AddWithValue("@lname", txtLastName.Text);
            cmd.Parameters.AddWithValue("@age", txtAge.Text);
            cmd.Parameters.AddWithValue("@state", cmbState.Text);
            cmd.Parameters.AddWithValue("@city", cmbCity.Text);
            cmd.Parameters.AddWithValue("@email", txtEmail.Text);
            if (rbtnFemale.Checked)
            {
                cmd.Parameters.AddWithValue("@sex", rbtnFemale.Text);
            }
            else
            {
                cmd.Parameters.AddWithValue("@sex", rbtnMale.Text);
            }
            cmd.Parameters.AddWithValue("@contactno", txtContactNo.Text);

            cmd.ExecuteNonQuery();
            FillGridWithPatient();
            Label1.Visible=true;
            Label1.Text="Inserted Successfully";
            btnEdit.Text = "Update";
        }
        catch (Exception ex)
        {
            Label2.Text = ex.ToString();
            Label2.Visible = true;
        }
        finally
        {
            if (conn.State == ConnectionState.Open)
            {
                conn.Close();
            }
        }

    }
}
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.