Here's a fixed version of your code:
string conStr = ConfigurationManager.ConnectionStrings["CStringCRM"].ToString();
using (SqlConnection conn = new SqlConnection(conStr))
using (SqlCommand cmd = new SqlCommand(@"SELECT top 1 ID FROM User order by ID desc", conn))
{
conn.Open();
using (SqlDataReader dr = command.ExecuteReader(CommandBehavior.CloseConnection))
{
if (dr.Read())
{
txtUID.Text = Convert.ToString(dr["ID"]);
}
}
}
- Consistent column name, as suggested by CPallini;
- Removed the un-used
DataTable
and dt.Load(dr)
, as suggested by CPallini and CodeMaster_Noob; - Wrapped the
SqlDataReader
in a using
block, and told it to close the connection when finished; - Added the required
dr.Read()
call before attempting to access values from the SqlDataReader
; - Replaced
dr["ID"].ToString()
with Convert.ToString(dr["ID"])
, in case the column value is null
;