如何从sql数据库表中将数据加载到文本框中

时间:2015-04-18 04:14:40

标签: c# mysql sql-server winforms

我遇到问题我无法将数据加载到查询从Windows窗体中获取的文本框中。 while循环无法执行。如何解决这个问题。或者没有任何错误或例外。内部命令无法执行调试器移动以捕获和完成。

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)
        {

        }

    }

2 个答案:

答案 0 :(得分:1)

哦什么。顶!使用参数化查询来避免SQL注入

connection

中提及你的conncection字符串

我希望问题是您在选择查询中错误txtEmployId.Text值和txtEmplyName.Text

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();
    }

答案 1 :(得分:1)

  1. 你的连线在哪里?如果它不在页面中,请包含一个。
  2. 打开Con.open()
  3. 之类的连接
  4. 使用参数化查询来避免sql注入,但这只是一个建议。
  5. 我认为代码的问题是连接字符串。打开try块内的连接。