Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rows in DataRow of Asp.net

Tags:

c#

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.

like image 238
user35 Avatar asked Nov 27 '25 09:11

user35


2 Answers

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.

like image 178
shree.pat18 Avatar answered Nov 29 '25 22:11

shree.pat18


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.

like image 20
suman Avatar answered Nov 29 '25 23:11

suman



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!