user35
user35

Reputation: 468

Rows in DataRow of Asp.net

Its kind of subjective question to ask but still i hope i will find help.
I was learning about merging two tables from database to a singe DataTable.Then i came accross the following block of code.

 DataTable mdt = new DataTable();

    mdt.Columns.Add("products");
    mdt.Columns.Add("price");


for (int i = 0; i < A.Rows.Count; i++)
            {
                DataRow dr = mdt.NewRow();
                dr["product"] = A.Rows[i]["product"].ToString();
                dr["price"] = A.Rows[i]["price"].ToString();
                //A is a DataTable 
                mdt.Rows.Add(dr);
            }

I can understand that the datas are being added to the row of a Datatable. This is what i understood: The column product of DataTable is assigned a value by dr["product"].Correct me if i am wrong.But how is this A.Rows[i]["product"].ToString(); working.

Upvotes: 3

Views: 3218

Answers (3)

suman
suman

Reputation: 728

Rows[i] represents the index to which the value is assigned.I mean for the first loop the value is 0,for second loop the value is 1.So for the firs loop the values of product and price are added to first row with index 0.Similarly for the second loop the values of product and price are added to the second row with index 1.
And for the second part ie ["product"].ToString(),its simply converting the value of product to string.

EDIT

Since A is a Datatable which is already filled.What we are doing with that statement is,we are taking the DataTables's i-th row from the collection,converting it to string and assigning it to the column "product" in the datarow.

Upvotes: 1

Spencer Waz
Spencer Waz

Reputation: 155

The ["product"].ToString() Is taking the value of the cell with the column name product, and converting it to a string to be assigned to your new row.

Upvotes: 0

shree.pat18
shree.pat18

Reputation: 21757

This should help:

A = DataTable
A.Rows = Collection of DataRows in A
A.Rows[i] = i-th row from collection
A.Rows[i]["product"] = Column "product" in row (return type of expression is object)

So when you do dr["product"] = A.Rows[i]["product"].ToString();, you are assigning the value of the product column of the current row from datatable A to the product column in your new data row. Similarly for the price column.

Upvotes: 3

Related Questions