我无法通过查询提取值并将其插入textbox
es
我要去哪里错了?
Request.QueryString.Get("ID_Persona");
string query = "SELECT ID,Nome,Cognome,Email,CodiceFiscale FROM Persona WHERE ID = @id";
using (SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["dbConnection"].ConnectionString))
{
SqlCommand cmd = new SqlCommand(query, con);
cmd.Parameters.AddWithValue("@ID","");
cmd.Parameters.AddWithValue("@Nome", TextBox1.Text);
cmd.Parameters.AddWithValue("@Cognome", TextBox15.Text);
cmd.Parameters.AddWithValue("@Email", TextBox20.Text);
cmd.Parameters.AddWithValue("@CodiceFiscale", TextBox22.Text);
con.Open();
cmd.ExecuteNonQuery();
}
答案 0 :(得分:3)
您需要使用ExecuteReader
来读取值,如下所示:
var connectionString = ConfigurationManager.ConnectionStrings["dbConnection"].ConnectionString;
string query = "SELECT ID,Nome,Cognome,Email,CodiceFiscale FROM Persona WHERE ID = @id";
using (SqlConnection con = new SqlConnection(connectionString))
{
using (var cmd = new SqlCommand(query, con))
{
cmd.Parameters.AddWithValue("@ID", Request.QueryString.Get("ID_Persona"));
con.Open();
using (var rdr = cmd.ExecuteReader())
{
if (rdr.Read())
{
//IDTextBox? = rdr["Id"].ToString(),
TextBox1.Text = rdr["Nome"].ToString(),
TextBox15.Text = rdr["Cognome"].ToString(),
TextBox20.Text= rdr["Email"].ToString(),
TextBox22.Text= rdr["CodiceFiscale"].ToString(),
}
}
}
}
答案 1 :(得分:2)
您应该使用ExecuteReader()
而不是ExecuteNonQuery()
,因为ExecuteNonQuery
用于DML操作。同样,您只需要传递ID值,然后说明为什么要将不必要的参数传递给查询。全部删除。下面的例子
SqlDataReader reader = cmd.ExecuteReader();
while (reader.Read())
{
Console.WriteLine(String.Format("{0}", reader["Email"]));
}
答案 2 :(得分:2)
我可以看到几个问题:
ExecuteReader()
而不是ExecuteNonQuery()
1
参数-@ID
;我怀疑它是否应该具有 empty 值。IDisposable
包裹到using
代码:
string query =
@"SELECT ID,
Nome,
Cognome,
Email,
CodiceFiscale
FROM Persona
WHERE ID = @id";
using (SqlConnection con = new SqlConnection(...))
{
con.Open();
using SqlCommand cmd = new SqlCommand(query, con)
{
// I doubt if you want empty Id here.
// I've assumed you want to pass ID_Persona
cmd.Parameters.AddWithValue("@ID", Request.QueryString.Get("ID_Persona"));
using (var reader = cmd.ExecuteReader())
{
if (reader.Read())
{
TextBox1.Text = Convert.ToString(reader["Nome"]);
TextBox15.Text = Convert.ToString(reader["Cognome"]);
TextBox20.Text = Convert.ToString(reader["Email"]);
TextBox22.Text = Convert.ToString(reader["CodiceFiscale"]);
}
}
}
}