Try:
using (SqlConnection con = new SqlConnection(strConnect))
{
con.Open();
using (SqlCommand com = new SqlCommand("SELECT iD, description FROM PurchaseTypes", con))
{
using (SqlDataReader reader = com.ExecuteReader())
{
while (reader.Read())
{
int id = (int) reader["iD"];
string desc = (string) reader["description"];
Console.WriteLine("ID: {0}\n {1}", iD, desc);
}
}
}
}
From the OP:
sql = "select amount from data where password='" + txtpassword.Text + "'";
cmd = new SqlCommand(sql, con);
if (rdbAdd.Checked == true)
{
if (txtpassword.Text.Length == 7)
{
con.Open();
SqlDataReader reader = cmd.ExecuteReader();
try
{
reader.Read();
amount=(int)reader["Amount"];
That is not the same: you do not check the return result of reader.Read() - if you have no data, it will return false and you will get an error if you try to use it, as you have seen.
In addition, do not concatenate strings to form dynamic SQL: you leave yourself wide open to an accidental or deliberate SQL Injection attack, which could destroy your database. Use parametrized queries instead:
sql = "select amount from data where password=@PW";
cmd = new SqlCommand(sql, con);
cmd.Parameters.AddWithValue("@PW", txtpassword.Text);
Oh, and don't store passwords in clear in your database: major security risk! :laugh: