How do I properly declair a parameter in the code below. Im getting underlines on “SelectCommand” Im not sure what im doing wrong.
public int GetTotalNumberOfAprovedPictureIds(string SexType)
{
string strConectionString = ConfigurationManager.AppSettings["DataBaseConnection"];
SqlConnection conn = new SqlConnection(strConectionString);
conn.Open();
SqlCommand oCommand = new SqlCommand("SELECT COUNT(1) AS Expr1 FROM MEMBERS INNER JOIN Picture ON MEMBERS.MemberID = Picture.MemberID WHERE (Picture.PicAproval = 1) AND (Picture.PicArchive = 0) AND (MEMBERS.MemberSex = @dSexType)", conn);
object oValue = oCommand.ExecuteScalar();
oCommand.SelectCommand.Parameters.Add("@dSexType", SqlDbType.Text);
oCommand.SelectCommand.Parameters["@dSexType"].Value = SexType;
conn.Close();
if (oValue == DBNull.Value)
{
return 0;
}
else
{
return Convert.ToInt32(oValue);
}
}
You are doing a couple of things wrong;
1) You are adding the parameter AFTER you execute the query
2) You are using the SelectCommand property when you don’t need to. In fact, you are probably confusing this with a DataAdapter object, which does have a SelectCommand property.
Instead, try:
I’d strongly urge you to use a “USING” statement when dealing with SqlConnection, SqlCommand and similar objects. It will ensure your connection is closed and disposed as soon as it leaves the scope, including after an exception.