How to load data into text-box from sql database t

2020-07-27 06:00发布

问题:

I have problem I can't able to load data into textboxes that the query fetch from database in windows form. The while loop cannot execute. how to solve this issue. or not have any error or exception. The inner commands cannot execute the debugger move to catch and finish.

private void btnCheck_Click(object sender, EventArgs e)
    {
        try
        {
             //  query = "SELECT Id, Emplname, CNIC, City, MobileNo, Address, Salary, DailyWage, CompanyId, Status FROM Employees where id = '" + labCompyId.Text + "'";
        query = "SELECT CNIC, City, MobileNo, Address, Salary, DailyWage, Status FROM  Employees WHERE (EmployId = '"+txtEmployId+"') AND (Emplname = '"+txtEmplyName+"')";
        SqlCommand  command1 = DBConnectivity.getCommandForQuery(query, connection);
        SqlDataReader reader1 = command1.ExecuteReader();


        while(reader1.Read())
       {
        this.txtCNIC.Text = (reader1["CNIC"].ToString());
        this.txtEmplyCity.Text = (reader1["City"].ToString());
        this.txtEmplyAddress.Text = (reader1["Address"].ToString());
        this.txtSalary.Text = (reader1["Salary"].ToString());
        this.txtDailyWage.Text = (reader1["DailyWage"].ToString());

            reader1.Close();
        }


        }
        catch (Exception ex)
        {

        }

    }

回答1:

Oh what.Stop!!! Use Parameterized query to avoid SQL Injection

Mention you conncection string in connection

I hope the problem is you have missesd txtEmployId.Text value and txtEmplyName.Text value in your select query

SqlConnection  connection= new SqlConnection(your Connection string);
string query = "SELECT CNIC, City, MobileNo, Address, Salary, DailyWage, Status   
       FROM  Employees WHERE EmployId =@EmpID AND Emplname = @Emplname ";
SqlCommand  command1 = new SqlCommand(query, connection); 
connection.Open();
command1.Parameters.AddWithValue("@EmpID",txtEmployId.Text);
command1.Parameters.AddWithValue("@Emplname",txtEmplyName.Text);
SqlDataReader reader1 = command1.ExecuteReader();


    while(reader1.Read())
   {
    this.txtCNIC.Text = (reader1["CNIC"].ToString());
    this.txtEmplyCity.Text = (reader1["City"].ToString());
    this.txtEmplyAddress.Text = (reader1["Address"].ToString());
    this.txtSalary.Text = (reader1["Salary"].ToString());
    this.txtDailyWage.Text = (reader1["DailyWage"].ToString());

        reader1.Close();
    }


回答2:

  1. Where is your connectionstring? If it is not in the page, include one.
  2. Open the connection like Con.open()
  3. Use parameterized query to avoid sql injection but that is just a suggestion.

The problem of the code is the connection string in my opinion.Open the connection inside the try block.