0

I have asp.net detailsview which inserts data into payment allocation table, however I want to run a update command that update data into s_transaction_enquiry table, which is done in C#. When I run the code, the update command runs first before the insert command so not data is put into the s_transaction_enquiry table.

I have created the update command to run when user click's on the insert button in the details view. The insert command is linked to the detailview's Sql Data source.

I have been told I can use "IsPostBack" property in the page_load but sure how to do this, is there anyone who could help me??

      protected void Page_Load(object sender, EventArgs e)
    {

        if (!IsPostBack)
        {
            string conn = "";
            string sqlCOmmand = "UPDATE s_transaction_enquiry, payment_allocation SET s_transaction_enquiry.payment_amount = payment_allocation.payment_amount, s_transaction_enquiry.payment_ref = payment_allocation.payment_ref, s_transaction_enquiry.payment_received_date = payment_allocation.payment_received_date WHERE payment_allocation.s_invoice_numer = s_transaction_enquiry.s_invoice_number AND payment_allocation.account_number = s_transaction_enquiry.account_number";
            conn = ConfigurationManager.ConnectionStrings["Conn"].ToString();
            UpdateRow(conn, sqlCOmmand);
        }


    }

    public void UpdateRow(string connectionString, string insertSQL)
    {
        using (OleDbConnection connection = new OleDbConnection(connectionString))
        {

            OleDbCommand command = new OleDbCommand(insertSQL);


            command.Connection = connection;

            try
            {
                connection.Open();
                command.ExecuteNonQuery();
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }

        }
    }

Insert statement from datasource:

  <asp:SqlDataSource ID="SqlDataSource2" runat="server" ConnectionString="<%$ ConnectionStrings:ConnectionString1 %>" DeleteCommand="DELETE FROM [payment_allocation] WHERE [payment_ref] = ?" ProviderName="<%$ ConnectionStrings:ConnectionString1.ProviderName %>" SelectCommand="SELECT * FROM [payment_allocation]" 
             InsertCommand="INSERT INTO [payment_allocation] ([payment_ref], [account_number], [account_ref], [allocate_date], [payment_amount], [payment_received_date], [s_invoice_numer]) VALUES (?, ?, ?, ?, ?, ?, ?)">

Button which invokes the insert statement:

  <asp:Button ID="Button1" runat="server" CausesValidation="True" CommandName="Insert" Text="Create"/>
  • IsPostBack is simply a flag thats raised on postbacks. like, if you click your button, it will post back to your aspx page and IsPostBack will be true. which means basically that IsPostBack will only be false when you first load the page, and will be true on page postbacks. also, page_load executes before the click event handler, so its supposed to be alright. is it possible that you have a different issue here? – Banana Mar 23 '14 at 13:14
  • you open the connection on page_load but u dont seem to close it, is this your full code? – Banana Mar 23 '14 at 13:15
  • I thought I closed the connection the Button1_click event, after the update command has run? Is another way to make sure the insert command on the aspx page runs first? – user3382674 Mar 23 '14 at 13:43
  • you have to close the connection there in page load after your done with your insert. you doing an action on page load you have to open/close it. or better, use a `using()` block on the connection in both button and page_load. also, i assume you want the insert to be executed only once, not every time you click a button, therefore use the `if(!IsPostBack )` to run it only when page first loads – Banana Mar 23 '14 at 13:50
  • lemme know if this works for you, so i can add it as an answer – Banana Mar 23 '14 at 13:51
  • Please can I get an example as im only a beginner at coding? – user3382674 Mar 23 '14 at 13:57
  • ive posted an answer, i hope it helps :) – Banana Mar 23 '14 at 14:18

1 Answers1

0

you should close your connection after every action. you have opened a connection on 'page_load' but didnt close it, and since page_load executes on every postback as well, which means every time you click your button, you attempt to open a connection again without closing it.

also notice that page_load executes before the button_click event handler therefore every time you click your button you open the connection without closing, and the trying to open it again in the click handler.

OleDbConnection is a disposable object, which means it implements the .dispose() function, which also means that it can be used in a using() statement .

the using() statement creates a new object and disposes of it after. you have a pretty good explanation on openning/closing/disposing of OleDbConnection in c# here on microsoft website: OleDbConnection Class

basically in order to adapt it to your code, you would want to do something like this, first put your database handling in a separate function for convenience and call it from page load::

    protected void Page_Load(object sender, EventArgs e)
    {
        string conn = "";
        string sqlCOmmand= "inset blablabla into blablabla";
        conn = ConfigurationManager.ConnectionStrings["Conn"].ToString();


        InsertRow(conn,sqlCOmmand);


    }


//taken from microsoft website
public void InsertRow(string connectionString, string insertSQL)
{
    using (OleDbConnection connection = new OleDbConnection(connectionString))
    {
        // The insertSQL string contains a SQL statement that 
        // inserts a new row in the source table.
        OleDbCommand command = new OleDbCommand(insertSQL);

        // Set the Connection to the new OleDbConnection.
        command.Connection = connection;

        // Open the connection and execute the insert command. 
        try
        {
            connection.Open();
            command.ExecuteNonQuery();
        }
        catch (Exception ex)
        {
            Console.WriteLine(ex.Message);
        }
        // The connection is automatically closed when the 
        // code exits the using block.
    }
}

alright, after this part is clear, off to the next one:

i assume you want to insert to the database only when your page loads right? and not after every button click. so you need to direct asp.net to only execute your code if its a first load and not a postback. you would want to change your page_load function to look like that:

protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            string conn = "";
            string sqlCOmmand = "inset blablabla into blablabla";
            conn = ConfigurationManager.ConnectionStrings["Conn"].ToString();
            InsertRow(conn, sqlCOmmand);
        }
    }

as for your click handler, you should create another function UpdateRow and do the same with a using() statement and put it in your click handler

Banana
  • 7,424
  • 3
  • 22
  • 43
  • I change my code (please see above) but it did not work. – user3382674 Mar 23 '14 at 14:58
  • can you be more specific as to how did it not work? did you get an exception? did you check your database to see if it was inserted? – Banana Mar 23 '14 at 15:02
  • No exception was given, it looked liked it worked until i checked the database and their was no data in the s_transaction_enquiry table. – user3382674 Mar 23 '14 at 15:06
  • according to your code it seems you are trying to update something, are you sure you didnt meant to do an "INSERT" statement first? is the data your updating exists? – Banana Mar 23 '14 at 15:38
  • The insert statement has already been created in the detailsview on the aspx page. – user3382674 Mar 24 '14 at 09:40
  • I want a "update" statement to run as well as the insert statement. But I need the detailsview's insert statement to work first before the update statement. – user3382674 Mar 24 '14 at 09:42
  • Try moving your insert statement to page_load – Banana Mar 24 '14 at 10:18
  • I can not is it part of the data source, please see above. – user3382674 Mar 24 '14 at 10:46
  • unfortunately my friend, if you have a look here http://msdn.microsoft.com/en-us/library/ms178472.aspx you can see that page_load code is executed before that sqkdatasource binds. therefore if you want it to execute before loading your code above, you have to either bind it manually in page_load or make the updating happen only on button_click. – Banana Mar 24 '14 at 11:03
  • Thank you, I can get the update to happen on button_click but it still executes the update command before the insert command :( – user3382674 Mar 24 '14 at 18:22
  • well if you make the insert happen on page_load, i mean using c# and not asp binding, then you can sort it out – Banana Mar 24 '14 at 18:37