从数据库中选择查询

时间:2015-11-01 11:46:55

标签: c# sql-server

我认为一切都很好,为什么数据不会显示在文本框中。我多次使用这段代码。那么这里有什么错误?我在Visual Studio 2012中工作。

string name = comboBox1.SelectedIndex.ToString();

query = "select *from Record Where Name='"+name+"'";
cmd = new SqlCommand(query, con);

con.Open();
SqlDataReader dr = cmd.ExecuteReader();

while (dr.Read())
{
     textBox1.Text =(dr["Items1"].ToString());
     textBox2.Text = (dr["Items1_Charge"].ToString());
     textBox3.Text = (dr["Items2"].ToString());
     textBox4.Text = (dr["Items2_Charge"].ToString());
     textBox5.Text = (dr["Items3"].ToString());
     textBox6.Text = (dr["Items3_Charge"].ToString());
     textBox7.Text = (dr["Items4"].ToString());
     textBox8.Text = (dr["Items4_Charge"].ToString());               
}

1 个答案:

答案 0 :(得分:1)

我怀疑*应该来自*。另外我建议使用where条件的参数,如下所示,特别是当有可能嵌入撇号时。还要注意我添加了HasRows,所以我们确信有些东西会回来。我还改变了从ComboBox获取当前值的方式

public void Sample()
{
    string name = comboBox1.Text;
    query = "select * from Record Where Name= @Name";

    cmd = new SqlCommand(query, con);
    cmd.Parameters.AddWithValue("@Name", name);

    con.Open();
    SqlDataReader dr = cmd.ExecuteReader();

    if (dr.HasRows)
    {
        while (dr.Read())
        {
            textBox1.Text = (dr["Items1"].ToString());
            textBox2.Text = (dr["Items1_Charge"].ToString());
            textBox3.Text = (dr["Items2"].ToString());
            textBox4.Text = (dr["Items2_Charge"].ToString());
            textBox5.Text = (dr["Items3"].ToString());
            textBox6.Text = (dr["Items3_Charge"].ToString());
            textBox7.Text = (dr["Items4"].ToString());
            textBox8.Text = (dr["Items4_Charge"].ToString());
        }
    }
}