Home > Back-end >  ASP.NET getting data from SQL Server
ASP.NET getting data from SQL Server

Time:11-19

I am trying to get the name of the employee from the database and fill it in the textbox for the respective employee id.

I tried this code but nothing is happening on the page. It just reloads and the textbox (name) is left blank only.

SqlConnection con = new SqlConnection(@"Data Source=DESKTOP-0FUUV7B\SQLEXPRESS;Initial Catalog=EmployeeDetails;Integrated Security=True");
con.Open();
           
SqlCommand cmd = new SqlCommand("select * from ProfessionalDetails where EmpId='" EmployeeId.Text "'", con);
          
SqlDataReader da = cmd.ExecuteReader();

while (da.Read())
{
    Name.Text = da.GetValue(1).ToString();
}
            
con.Close();

CodePudding user response:

As mentioned above in comments, you have lot of issues.

you should use using with the connection to dispose of them.

You should use parameterized queries to avoid SQL injection.

Put your code in try catch so that you can easily identify the root cause of the issue.

Define the connection string in config file three than defining in the c# code.

You don’t need to select all the columns. And please avoid select * in the query, instead just write your column name, as you want to select only one column here.

You can use ExecuteScalar, it’s used when you are expecting single value.

And first make sure that textbox has the expected value when you are calling this query.

CodePudding user response:

Better solution is to execute the sql statement through Parameterized value. The details of that process is given below:

 using (SqlConnection con = new SqlConnection(live_connectionString))
        {
            using (SqlCommand cmd = new SqlCommand("Query", con))
            {
                con.Open();
                cmd.CommandType = CommandType.Text;
                cmd.Parameters.AddWithValue("@EmpId", employeeId);

                SqlDataAdapter da = new SqlDataAdapter();
                da.SelectCommand = cmd;
                var ds = new DataSet();
                da.Fill(ds);
             

                string? name = ds.Tables[0].Rows[1]["Variable name"].ToString();
              
              Name.Text =name;
            };
        }
    }
  • Related