[英]Is my logic correct? I'm trying to get data from combobox(dropdownlist) and use that data to search and display information in checkedlistbox
I keep getting this error whenever I do the search: Invalid column name 'datafromcombobox' 每当我执行搜索时,我都会不断收到此错误:无效的列名'datafromcombobox'
I tried hardcode the data in my SQL query and it works. 我尝试对SQL查询中的数据进行硬编码,并且可以正常工作。 Any idea what's wrong with my code? 知道我的代码有什么问题吗?
Here's the code: 这是代码:
string selectedMedication = cboMedicationType.SelectedItem.ToString();
string strMedications = "SELECT medicationName FROM MEDICATION WHERE medicationType= (" + selectedMedication + ")";
SqlCommand cmdMedications = new SqlCommand(strMedications, connection);
connection.Open();
SqlDataReader readMedications = cmdMedications.ExecuteReader();
while (readMedications.Read())
{
string medicationVar = readMedications["medicationName"].ToString();
clbMedication.Items.Add(medicationVar, true);
}
readMedications.Close();
connection.Close();
I think you just forgot the quotes in your query. 我认为您只是忘记了查询中的引号。 This should work : 这应该工作:
string strMedications = "SELECT medicationName FROM MEDICATION WHERE medicationType= ('" + selectedMedication + "')";
I would do it this way: 我会这样:
using (SqlCommand cmdMedications = new SqlCommand(strMedications, connection))
{
string strMedications = "SELECT medicationName FROM MEDICATION WHERE medicationType = @selectedMedication;
command.Parameters.AddWithValue("selectedMedication", cboMedicationType.SelectedItem.ToString());
connection.Open();
using (SqlDataReader readMedications = cmdMedications.ExecuteReader())
{
while (readMedications.Read())
{
string medicationVar = readMedications["medicationName"].ToString();
clbMedication.Items.Add(medicationVar, true);
}
}
connection.Close();
}
I changed several things: 我改变了几件事:
using
in your code ( see this article ), because then you don't need to close
or dispose
objects--the using
statements take care of that. 通常最好在代码中使用using
( 请参阅本文 ),因为那样就不需要close
或dispose
对象了using
语句可以解决这一问题。 Let me know if I can clear up something else. 让我知道是否可以清除其他内容。 I hope this helps! 我希望这有帮助!
PS I mostly typed this without debugging so there might be some small things you might have to tweak, but I thing you should get the gist of it. PS我主要是在没有调试的情况下键入此内容,因此可能需要调整一些小东西,但我认为您应该了解它的要旨。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.