DISABLE ADBLOCK

ADBlock is blocking some content on the site

ADBlock errore
Results found: 

Question

I have written the following code for a login page:

SqlConnection con=new SqlConnection("Data Source=.\\sqlexpress;Initial Catalog=MLM;Integrated Security=True");
SqlCommand com=new SqlCommand("select UserName,Login_Password from RegistrationForm",con); 

con.Open();
SqlDataReader rs = com.ExecuteReader(); 

while (rs.Read()) 
{
   if ((rs[0].ToString() == T1.Text) && (rs[31].ToString()== T2.Text))
   {
      string s1 = T1.Text;
      Response.Redirect("HOME.aspx?UserName=" + s1);
      return;
   }
   else 
   {
      Response.Write("Unsuccessful Login");
      T2.Text = "";
      T2.Focus();
   }
}
rs.Close();
com.ExecuteNonQuery();
con.Close(); 

The error I get is Array index out of bound....but when I take rs[1] instead of rs[31], then error is like an unsuccessful login.

Solution

manjusha s wrote:
.bt when i take rs[1] instead of rs[31],then error is like unsuccessful login


Well, that's what your code is supposed to say when you type a wrong password. This is what happens, whit rs[2];

Here you check whether username and password combination are present in the database
if ((rs[0].ToString() == T1.Text) && (rs[31].ToString()== T2.Text))
If they don't exist, then the computer will execute the else-part;
else<br />{<br />Response.Write("Unsuccessful Login");<br /><br />T2.Text = "";<br />T2.Focus();<br />}<br />
There is your message. Shouldn't happen when you use a password that is in the database.

Now, when you simply change the number of the index to 31, your code becomes broken; there aren't 31 fields in that query, so it tries to read from memory that ain't there.
select UserName,Login_Password from RegistrationForm
returns two fields, not 31.

If you like, leave us your opinion

Was the article helpful and is it translated correctly?

OTHER TIPS

hello,
i agree with eddy vluggen what he said is right also keep this in mind that you are using .net although by looking at ur code i feel ur using c# which will definitely check of the bounds of array, it's not like c where bounding checking is not their so make sure that rs[31] of yours is present...

Thanks & Regards
Radix:rose:

The sqldatareader RS Should have 31 columns otherwise exception will occur. you can simply pass on the column name to check the values.

I would say do comparison as below.

if ((rs["UserName"].ToString().ToLower() == T1.Text.ToLower())            &&(rs["Login_Password"].ToString()== T2.Text))

The statement is pretty simple.
1. Its readable as well as lets you know, what you are comparing.
2. converts username to lower and then compares. Advantage of this is, user need not to keep username letter cases to keep in mind.

this will work properly
if ((rs[0].ToString() == T1.Text) && (rs[1].ToString()== T2.Text))

Licensed under: CC-BY-SA with attribution
Not affiliated with codeproject.com