[英]When trying to retrieve data from the database I get an error “InvalidOperationException was unhandled”
I have a form named Form1
: 我有一个名为Form1
的表单:
There is one ComboBox
and one TextBox
, when I select US$ from the ComboBox
then it must retrieve data from the database and display 150 in the TextBox
. 有一个ComboBox
和一个TextBox
,当我从ComboBox
选择US $时,它必须从数据库中检索数据并在TextBox
显示150。
This is myform code: 这是myform代码:
For ComboBox
; 对于ComboBox
;
namespace PCJ_System
{
public partial class Form1 : Form
{
SqlConnection conn;
SqlCommand cmd;
SqlDataReader dr;
public Form1()
{
InitializeComponent();
}
private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
string str = "server = DESKTOP-LKEG8FM\\SQLEXPRESS;initial catalog= PCJ_DB ; Integrated Security=True;";
SqlConnection conn = new SqlConnection(str);
conn.Open();
conn = new SqlConnection(str);
string GetData = "Select [FC_Rate] from Forcur where FC_TYPE ='" + comboBox1.Text + "' ";
cmd = new SqlCommand(GetData, conn);
var returnValue = cmd.ExecuteScalar();
textBox1.Text = returnValue.ToString();
conn.Close();
}
}
}
My database table Forcur: 我的数据库表Forcur:
ID |FC_TYPE |FC_RATE|
1 US$ 150
2 UK# 210
What's wrong with my code? 我的代码出了什么问题?
This might not be the exact answer you are looking for, but you need to take care of following: 这可能不是您正在寻找的确切答案,但您需要注意以下事项:
1) Assign DB connection string to SqlConnection
object and open connection. 1)将DB连接字符串分配给SqlConnection
对象并打开连接。
2) Since you are assigning one value to textbox, you need to use ExecuteScalar
instead of ExecuteReader
2)由于您要为文本框分配一个值,因此需要使用ExecuteScalar
而不是ExecuteReader
Once you fix this, you should get the desired result. 解决这个问题后,您应该得到所需的结果。
Example: 例:
conn=new SqlConnection(connectionStringHere);
conn.Open();
string GetData = "Select [FC_Rate] from Forcur where FC_TYPE ='" + comboBox1.Text + "' ";
cmd = new SqlCommand(GetData, conn);
var returnValue = cmd.ExecuteScalar();
textBox1.Text = returnValue.ToString();
conn.close();
Note: You still have SQL injection attack open in your SQL query. 注意:您仍然在SQL查询中打开SQL注入攻击。 Try using varables instead to stop that. 尝试使用变量来阻止它。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.