Tutorial on using stored procedures in formview

advertisements

I'm looking for some tutorials which will help me to understand how to use stored procedures in the code behind file for updating the values displayed using formview. I searched the internet and didn't find good ones. If anyone can give me some links or some outline as how to do this I'll appreciate it. Thanks


Firstly, as Mavrinsky says, doing it in the codebehind isn't ideal - better to look at putting your data access code in a separate class entirely, in order to reduce coupling in your code.

However, this might help get you started: it calls an SP called GetProduct and gives you a DataTable.

public class ProductDB
{
    private ConnectionStringSettings connectionString;
    private DataTable ProductTable = new DataTable();

    public ProductDB()
    {
        connectionString = ConfigurationManager.ConnectionStrings["MyConnectionString"];
    }

    public ProductDB(ConnectionStringSettings connectionString)
    {
        this.connectionString = connectionString;
    }

    public DataTable GetProduct(int Id)
    {
        SqlConnection con = new SqlConnection(connectionString.ConnectionString);
        SqlCommand cmd = new SqlCommand("GetProduct", con);
        cmd.CommandType = CommandType.StoredProcedure;

        cmd.Parameters.Add(new SqlParameter("@Id", SqlDbType.Int, 4));
        cmd.Parameters["@Id"].Value = Id;

        try
        {
            SqlDataAdapter da = new SqlDataAdapter(cmd);
            da.Fill(ProductTable);
            return ProductTable;
        }
        catch (SqlException err)
        {
            throw;
        }
        finally
        {
            con.Close();
        }
    }
}