Share via


how to loop datatable and display results in a gridview?

Question

Wednesday, August 4, 2010 12:13 AM

This is my code in looping the reults from datable from serverA but it display the last results from serverA.

Datatable: data

partnumber Quanity

001             -      1

002             -         2

Result Datagridview:

SerialNumber PArtnumber
2                          002

3                         002

This is my Code:

foreach (DataRow recordFromServer in data.Rows) { try {

                            SqlCommand allocmd = new SqlCommand("sp_AllocateSerial", conn2); 

//Select TOP(@Quantity)serialnumber,partnumber where Partnumber=@Part allocmd.CommandType = CommandType.StoredProcedure;

                            DataTable Select = new DataTable(); 

                            SqlDataAdapter dap1 = new SqlDataAdapter(); 

                            allocmd.Parameters.AddWithValue("@Part", recordFromServer["PARTNUMBER"]); 

                            allocmd.Parameters.AddWithValue("@Limit", recordFromServer["QUANTITY"]); 

                            dap1.SelectCommand = allocmd; 

                            dap1.Fill(Select); 

 

                               this.dataGridView2.DataSource = Select; 

 

                        } 

 

                        catch (Exception ee) 

                        { 

                            MessageBox.Show(ee.Message); 

                        } 

                        finally 

                        { 

                            if (con3.State == ConnectionState.Open) con3.Close(); 

                        } 

 

                    } 

I need to have this results: Example:

Datatable: data

partnumber Quanity

001             -     1

 002             -      2

Result Datagridview:

SerialNumber PArtnumber

 1                    -    001

2                    -     002

 3                    -    002

All replies (3)

Wednesday, August 4, 2010 1:40 AM âś…Answered

Try this:

dataGridView1.Columns.Add( "SerialNumber", "SerialNumber" );
dataGridView1.Columns.Add( "PartNumber", "PartNumber" );
int index = 0;

foreach ( DataRow drow in data.Rows )
{
    for ( int i = 0; i < ( int )drow["quantity"]; i++ )
    {
        dataGridView1.Rows.Add();
        dataGridView1.Rows[index].Cells[0].Value = index + 1;
        dataGridView1.Rows[index].Cells[1].Value = drow["partnumber"];
        index++;
    }
}

Wednesday, August 4, 2010 1:19 AM

Hello.

 

You are setting the DataSource of the grid for each row.

You must use an storage (for example a List<>) to add all the retrieved rows and then assign it to the DataSource.


Wednesday, August 4, 2010 3:18 AM

Can you give me an Example? I am new in C#