I have setup my loop to loop through textboxes and fill the according textboxes with data it retrives, if seems to work fine, but there is a problem with opening and closing the connection below is my code
int i = 0;for (i = 1; i <= 3; i++){
//This gets the stock ID from the textbox.
string stock_ID = ((TextBox)Panel1.FindControl("txtID" + i.ToString())).Text;//This is the sql statement.
string sql ="SELECT [n_or_sh], [title], [cost_price], [selling_price] FROM tbl_stock WHERE stock_ID = " + stock_ID;
//This creates a sql command which executes the sql statement.
SqlCommand sqlCmd =newSqlCommand(sql, myConn);
myConn.Open();
//This is a reader for the results to go in.
SqlDataReader dr = sqlCmd.ExecuteReader();//This reads the first result from the sqlReader
dr.Read();
//This sets the title label text to the value of the description column.
TextBox currentBox1 = (TextBox)Panel1.FindControl("txtDesc" + i);string strtxtDesc = currentBox1.Text;
strtxtDesc = dr["title"].ToString();
}// end of loop
myConn.Close();
}// end of button click
i have tried putting the myConn.Close() in different places but it dosnt seem to work!
any advice or tips ?
Regards
Jez
1. You should use SqlParameter object to pass your ID. This makes the sql query optimizer to keep your query optimized for future uses, and takes you out of the sql injection attack risk.
2. You should close the SqlDataReader before closing the connection. Try dr.Close() (or better, dr.Dispose() )
3. For best practice, you should also dispose your sql connection. Try myConn.Dispose() (after closing it)
No comments:
Post a Comment