Bert
Bert

Reputation: 1029

Can't Get value from database in ASP.net

Hi can you help me with this??

I have this code and i want to display the result of my query into my 3rd Textbox but it not displaying.

string query = "SELECT UserID FROM [IBSI].[sec].[Users] WHERE UserName = '" + TextBox2.Text + "'";

if (query != null)
{
  using (SqlConnection conn = new SqlConnection(connect))
  {
    using (SqlCommand cmd = new SqlCommand(query, conn))
    {

      conn.Open();
      SqlDataReader rdr = cmd.ExecuteReader();
      if (rdr.HasRows)
      {
        while (rdr.Read())
        {

         TextBox3.Text=rdr["UserID"].ToString() ;


        }
      }
    }
  }
}

But then i just use this query without the where condition i can see the output;

string query = "SELECT UserID FROM [IBSI].[sec].[Users]";

Thanks in advance

Upvotes: 0

Views: 364

Answers (3)

Dmitry Reznik
Dmitry Reznik

Reputation: 6862

I'd recommend using parameterized queries for this task. Also, generating sql code from user input (like text boxes/memos) is prone to sql injections (user may enter any sql code into the textbox that may damage database data), so it'd be great to validate input data.

Sample parameter usage is like this:

string query = "SELECT UserID FROM [IBSI].[sec].[Users] WHERE UserName = @1";
if (query != null)
{
    using (SqlConnection conn = new SqlConnection(connect))
    {
        using (SqlCommand cmd = new SqlCommand(query, conn))
        {
            SqlParameter p1 = new SqlParameter("@1", TextBox2.Text);
            cmd.Parameters.Add(p1);
            conn.Open();
            SqlDataReader rdr = cmd.ExecuteReader();
            if (rdr.HasRows)
            {
                while (rdr.Read())
                {
                    TextBox3.Text=rdr["UserID"].ToString() ;
                }
            }
        }
    }
}

Upvotes: 2

ankit rajput
ankit rajput

Reputation: 182

ey Bert change in your code as follows:

string query = "SELECT UserID FROM [IBSI].[sec].[Users] WHERE UserName= '"+TextBox2.Text+ "'";       

if (query != null)     
{     
  using (SqlConnection conn = new SqlConnection(connect))     
  {     
    using (SqlCommand cmd = new SqlCommand(query, conn))     
    {   
      conn.Open();     
      int UserId;
      UserId=Convert.ToInt32(cmd.ExecuteScalar());
      TextBox3.Text=UserId.ToString() ;        
    }     
  }     
}     

Upvotes: 0

Publius
Publius

Reputation: 1224

Step through the debugger and verify that your query is returning results.

Upvotes: 0

Related Questions