I have a form named 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
.
This is myform code:
For 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:
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.
2) Since you are assigning one value to textbox, you need to use ExecuteScalar
instead of 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. Try using varables instead to stop that.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.