我收到错误消息:
Invalid attempt to call MetaData when reader is closed.
它指向这段代码:
--> txtMname.Text = dr1["Crew_Mname"].ToString();
下面的代码是我的中间名comboBox,如果找到结果,它将填写所有必要的textboxex。
private void txtMname_SelectedIndexChanged(object sender, EventArgs e)
{
txtMname.Items.Clear();
txtMname.Text = "";
econ = new SqlConnection();
econ.ConnectionString = emp_con;
econ.Open();
ecmd = new SqlCommand("SELECT Crew_Lname, Crew_Fname, Crew_Mname, Crew_Add1, Crew_Add2, Crew_Contact, Crew_Bdate, Rank_Name FROM CREW C, SKILL_RANK SR WHERE C.Rank_Id = SR.Rank_Id AND Crew_Lname like '" + Convert.ToString(txtLname.Text) + "%' AND Crew_Fname like '" + Convert.ToString(txtFname.Text) + "%'", econ);
ecmd.CommandType = CommandType.Text;
ecmd.Connection = econ;
dr1 = ecmd.ExecuteReader();
while (dr1.Read())
{
txtLname.Text = dr1["Crew_Lname"].ToString();
txtFname.Text = dr1["Crew_Fname"].ToString();
txtMname.Text = dr1["Crew_Mname"].ToString();
txtAddress.Text = dr1["Crew_Add1"].ToString();
txtAddress1.Text = dr1["Crew_Add2"].ToString();
txtContact.Text = dr1["Crew_Contact"].ToString();
dtpBdate.Text = dr1["Crew_Bdate"].ToString();
comRank.Text = dr1["Rank_Name"].ToString();
}
econ.Close();
}
还有一件事,每当我搜索具有相同单词的单词时,我也会得到同样的错误 我搜索过 约翰
然后在我的DB中有像John Michael,John Emmanuel这样的名字
当我在我的comboBox中单击John这个词时,显示错误并填写了John Michael的名字..我应该怎么做..请帮助..我知道他们的代码中存在问题.. < / p> 谢谢大家。 BTW Im使用VS2010 C#和SQL Server 2005
答案 0 :(得分:0)
不知道,尝试使用参数化查询并正确处理一次性资源,如连接,命令和读者:
using (var con = new SqlConnection(emp_con))
using (var cmd = con.CreateCommand())
{
con.Open();
cmd.CommandText =
@"
SELECT
Crew_Lname,
Crew_Fname,
Crew_Mname,
Crew_Add1,
Crew_Add2,
Crew_Contact,
Crew_Bdate,
Rank_Name
FROM
CREW C,
SKILL_RANK SR
WHERE
C.Rank_Id = SR.Rank_Id
AND
Crew_Lname LIKE @lName
AND
Crew_Fname LIKE @fName
";
cmd.Parameters.AddWithValue("@lName", txtLname.Text + "%");
cmd.Parameters.AddWithValue("@fName", txtFname.Text + "%");
using (var reader = cmd.ExecuteReader())
{
while (reader.Read())
{
txtLname.Text = reader.GetString(reader.GetOrdinal("Crew_Lname"));
txtFname.Text = reader.GetString(reader.GetOrdinal("Crew_Fname"));
txtMname.Text = reader.GetString(reader.GetOrdinal("Crew_Mname"));
txtAddress.Text = reader.GetString(reader.GetOrdinal("Crew_Add1"));
txtAddress1.Text = reader.GetString(reader.GetOrdinal("Crew_Add2"));
txtContact.Text = reader.GetString(reader.GetOrdinal("Crew_Contact"));
// Remark: if the Crew_Bdate is a datetime field in your database
// you should use reader.GetDateTime instead of reader.GetString
dtpBdate.Text = reader.GetString(reader.GetOrdinal("Crew_Bdate"));
comRank.Text = reader.GetString(reader.GetOrdinal("Rank_Name"));
}
}
}