Click here to Skip to main content
15,887,338 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
I am write the code for login page in asp.net web application also i am use session.
For login i am used my user registration database where in this table users all data save like name, gender,email etc. i am getting errors like this-"There is no row at position 0." in error dialogBox.


the error is shows this line-
username = ds.Tables[0].Rows[0]["Name"].ToString();
          repass = ds.Tables[0].Rows[0]["Re_password"].ToString();

Please anyone help me.Thank You...
my database table difinition is-
id	numeric(18, 0)	Unchecked
Name	nvarchar(100)	Checked
Gender	nvarchar(MAX)	Checked
Contcats	nvarchar(100)	Checked
EmailId	nvarchar(100)	Checked
Address	nvarchar(MAX)	Checked
Password	nvarchar(50)	Checked
Re_password	nvarchar(50)	Checked
		Unchecked


where id is primary key and set to idtenification. regarding this i am used Name and Re_password coloumn for login

What I have tried:

  protected void Button1_Click(object sender, EventArgs e)
        {
            String con = "Data Source=HOME-PC\\SQLEXPRESS;Initial Catalog=NoveltySystem;Integrated Security=True;Pooling=False";
            SqlConnection scon = new SqlConnection(con);
            String myquery = "select * from userSignup_db where Name='"+ uname.Text +"'";
            SqlCommand cmd = new SqlCommand();
            cmd.CommandText = myquery;
            cmd.Connection = scon;
            SqlDataAdapter da = new SqlDataAdapter();
            da.SelectCommand = cmd;
            DataSet ds = new DataSet();
            da.Fill(ds);
            String username;
            String repass;

            if (ds.Tables[0].Rows.Count > 0)
            {
            username = ds.Tables[0].Rows[0]["Name"].ToString();
            repass = ds.Tables[0].Rows[0]["Re_password"].ToString();
            scon.Close();
            if (username == uname.Text && repass == TextBox2.Text)
            {
                Session["Name"] = username;
            
               
                Response.Redirect("UserCPanel.aspx");
            }
            else
            {
                ClientScript.RegisterStartupScript(Page.GetType(), "validation", "<script language='javascript'>alert('Please Check Your Login Details..')</script>");
            }
}
}
Posted
Updated 5-Feb-19 21:40pm
v2
Comments
F-ES Sitecore 5-Feb-19 10:12am    
Use the debugger to find out how many rows are in ds.Tables[0].Rows

Easy, find out why your query didn't return any rows from the database.

There's "no row at position 0" because there's no data in the table.

Also, NEVER build an SQL query using string concatenation like that. Always use parameters. Google for "SQL Inject Attack" to find out why what you did is so bad. Then Google for "C# parameterized queries" to find out what to do about it.
 
Share this answer
 
Comments
Maciej Los 5-Feb-19 11:11am    
5ed!
Problem 1:
For starters, don't do it like that! Never concatenate strings to build a SQL command. It leaves you wide open to accidental or deliberate SQL Injection attack which can destroy your entire database. Always use Parameterized queries instead.

When you concatenate strings, you cause problems because SQL receives commands like:
SQL
SELECT * FROM MyTable WHERE StreetAddress = 'Baker's Wood'
The quote the user added terminates the string as far as SQL is concerned and you get problems. But it could be worse. If I come along and type this instead: "x';DROP TABLE MyTable;--" Then SQL receives a very different command:
SQL
SELECT * FROM MyTable WHERE StreetAddress = 'x';DROP TABLE MyTable;--'
Which SQL sees as three separate commands:
SQL
SELECT * FROM MyTable WHERE StreetAddress = 'x';
A perfectly valid SELECT
SQL
DROP TABLE MyTable;
A perfectly valid "delete the table" command
SQL
--'
And everything else is a comment.
So it does: selects any matching rows, deletes the table from the DB, and ignores anything else.

So ALWAYS use parameterized queries! Or be prepared to restore your DB from backup frequently. You do take backups regularly, don't you?

And concatenating strings on a login page? That's just plain asking for your DB to be deleted as I don't even have to sign up to do it!

Problem 2:
Never store passwords in clear text - it is a major security risk. There is some information on how to do it here: Password Storage: How to do it.[^]

Problem 3:
This is the one you noticed, and it's the trivial one: no records match your query, so there are no rows returned. No rows returned, means you get an error saying "you can't use a row that doesn't exist" which is what "There is no row at position 0" means.

But fix the first two throughout your app or your DB is toast (and you are wide open to massive fines for GDPR failings).
 
Share this answer
 
Comments
Maciej Los 5-Feb-19 11:11am    
5ed!
insted of this code i am improved and use this code for session wise login thats work

protected void Button1_Click(object sender, EventArgs e)
       {
           String constring = ConfigurationManager.ConnectionStrings["NoveltySystemConnectionString"].ConnectionString;

           SqlConnection  con = new SqlConnection(constring);
           str = "Select count(*) from userSignup_db where Name='" + uname.Text + "'and Re_password='" + repsw.Text + "'";
           cmd = new SqlCommand(str, con);
           cmd.Parameters.AddWithValue("Name",uname.Text);
           cmd.Parameters.AddWithValue("Re_password",repsw.Text);
           SqlDataAdapter sda = new SqlDataAdapter(cmd);
           DataTable dt = new DataTable();
           sda.Fill(dt);
           con.Open();
           cmd.ExecuteNonQuery();
           con.Close();
           if(dt.Rows.Count>0)

               {
                   Session["id"] = uname.Text;
                   Response.Redirect("UserCPanel.aspx");
                   Session.RemoveAll();
               }

               else
               {
                   ClientScript.RegisterStartupScript(Page.GetType(), "validation", "<script language='javascript'>alert('Please Check Your Login Details..')</script>");
               }
           }
 
Share this answer
 
Comments
Richard Deeming 6-Feb-19 12:35pm    
So you didn't read either of the other solutions then? 🤦‍♂️

Your code is vulnerable to SQL Injection[^]. NEVER use string concatenation to build a SQL query. ALWAYS use a parameterized query.
Everything you wanted to know about SQL injection (but were afraid to ask) | Troy Hunt[^]
How can I explain SQL injection without technical jargon? | Information Security Stack Exchange[^]
Query Parameterization Cheat Sheet | OWASP[^]

You're storing passwords in plain text. Don't do that:
Secure Password Authentication Explained Simply[^]
Salted Password Hashing - Doing it Right[^]

And why are you re-inventing the wheel? ASP.NET has several perfectly good authentication systems built-in - for example, ASP.NET Identity[^]

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900