Trying to access a SQL Server database to display a single line in c #

advertisements

I'm trying to access a SQL Server database and display a single row using C#. I'm having trouble figuring out how to properly do this. Please help. Thank you.

public Form1()
{
    InitializeComponent();

    string connectionString = "Data Source=localhost \\SqlExpress;Initial Catalog=MMABooks;" + "Integrated Security=True";
    SqlConnection connection = new SqlConnection(connectionString);

    string selectStatement = "SELECT ProductCode " + "FROM Products " + "WHERE ProductCode = @ProductCode";
    SqlCommand selectCommand = new SqlCommand(selectStatement, connection);

    selectCommand.Parameters.Add("@ProductCode");

    connection.Open();

    SqlDataReader reader = selectCommand.ExecuteReader(CommandBehavior.SingleRow);

    reader.Read();

    txtDisplay.Text = reader["ProductCode"].ToString();
}


Looks like you are passing the parameter productcode to the query and returning the same as result. Please make the scenario clear. if you need to pass the product code and get the same from table, what you can do is :

 public Form1()
{
    InitializeComponent();

    string connectionString = "Data Source=localhost \\SqlExpress;Initial Catalog=MMABooks;" + "Integrated Security=True";
    Object returnValue;
    SqlConnection connection = new SqlConnection(connectionString);

    string selectStatement = "SELECT Top 1 ProductCode " + "FROM Products " + "WHERE ProductCode = @ProductCode";
    SqlCommand selectCommand = new SqlCommand(selectStatement, connection);

    selectCommand.Commandtype = CommandType.Text;
    connection.Open();

    returnValue = selectCommand.ExecuteScalar();
    connection.Close();
    txtDisplay.Text = returnValue.ToString();

}