views:

554

answers:

3

Which is recommended

while (reader.Read())  
{
    table.Rows.Add(
            new object[] { reader[0], reader[1], reader[2], reader[3] }
    );  
    table.AcceptChanges();
}

or

while (reader.Read())  
{
    table.Rows.Add(
            new object[] { reader[0], reader[1], reader[2], reader[3] }
    );  
}  
table.AcceptChanges();

Note where the table.AcceptChanges is placed.


EDIT 1

Here is the code block:

protected void Page_Load(object sender, EventArgs e)
{
    IDataReader reader = cust.GetCustomerOrderSummary("99999");
    using (DataSet ds = new DataSet())
    {
        using (DataTable table =
                new DataTable { TableName = "OrderSummary" })
        {
            DataColumn idColumn = table.Columns.Add("number", typeof(int));
            table.Columns.Add("name", typeof(string));
            table.Columns.Add("quantity", typeof(int));
            table.Columns.Add("prev_quantity", typeof(int));
            table.PrimaryKey = new DataColumn[] { idColumn };
            while (reader.Read())
            {
                table.Rows.Add(
                  new object[]{ reader[0], reader[1], reader[2], reader[3] }
                );
                table.AcceptChanges();
            }
            ds.Tables.Add(table);
            rptCustomerOrder report =
                    new rptCustomerOrder { DataSource = ds };
            ReportViewer1.Report = report;
        }
    }
}


EDIT 2
After reading the MSDN article here I decided to place the AcceptChanges() outside the loop based on the following statement (from the article):

Calling AcceptChanges at the DataTable level causes the AcceptChanges method for each DataRow to be called.

+1  A: 

This really depends on what your table object is and what AcceptChanges is doing. In general I would say the secodn approach is more efficent if you can call AcceptChanges only once and have it do its work.

Again this is in general because I do not know what object you actually dealing with. But doing things inside loops is usually more expensive because you do it more often but your table object might require you to accept changes between each row in which case you have no choice.

JoshBerke
I updated the post.
Saif Khan
Doing it afterwards, should be slighly more efficent; however after reading MSDN. I'm not sure if you even need to call this method
JoshBerke
+1  A: 

I'm assuming AcceptChanges is when you actually commit your data?

The first way is less efficient in this case than the second, but is safer since there is less chance of you losing data if your read is interrupted at some point.

yx
I was thinking this, however I am not familiar with the AcceptChanges() so I am not sure exactly if it should go inside the loop or outside the loop. You have a point wiht the loss of data.
Saif Khan
A: 

Are you sure you need to be calling the AcceptChanges method at all? I've done similar and I've never had to use it.

Jagd