Reputation: 685
Below is the code for combo box selected value change. It is supposed to pick up a value from DB and display it in a text box.
protected void cmbPujaName_SelectedIndexChanged(object sender, EventArgs e)
{
SqlConnection con2 = null;
con2 = new SqlConnection(ConfigurationManager.ConnectionStrings["SRKBSDB"].ConnectionString);
SqlDataAdapter pamt = new SqlDataAdapter("select Amount from PoojaDietyMaster where PoojaName =" + cmbPujaName.SelectedValue, con2);
DataSet pamtds = new DataSet();
pamt.Fill(pamtds); ......... Error shown here...........
txtAmount.Text = pamtds.Tables[0].Rows[0]["Amount"].ToString();
}
Upvotes: 0
Views: 81
Reputation: 85
It's a better practice to write a query using SqlCommand parameters by mentioning proper datatype to avoid sql injection attacks. Try to handle null values as well.
SqlDataAdapter pamt = new SqlDataAdapter("select Isnull(Amount,0.0) Amount from PoojaDietyMaster where PoojaName = @name", con2);
pamt.SelectCommand.Parameters.Add("@name",SqlDbType.VarChar).Value = cmbPujaName.SelectedValue.tostring();
DataSet pamtds = new DataSet();
pamt.Fill(pamtds);
Upvotes: 0
Reputation: 66389
You're missing quotes but... do not do that like this. This way is like leaving your door wide open and invite thieves inside for a tea party. Or SQL Injection attack, inviting hackers to steal your whole database and/or server and take full control over it.
Have such code instead:
SqlDataAdapter pamt = new SqlDataAdapter("select Amount from PoojaDietyMaster where PoojaName = @name", con2);
pamt.SelectCommand.Parameters.AddWithValue("@name", cmbPujaName.SelectedValue);
DataSet pamtds = new DataSet();
pamt.Fill(pamtds);
This way you won't have to mess around with quotes, plus you're better protected against hackers.
Upvotes: 4