Rows in DataRow of Asp.net - c#

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.

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.

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.

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.

Related

retrieving Column cells value from datagridview C#

I can't figure out how to solve this. I want to calculate in datagridview
Column 3 like this
using C#
Check this
int sum = 0;
for(int i=0;i<dataGridView1.Rows.Count;i++)
{
sum += Convert.ToInt32(dataGridView1.Rows[i].Cells[0].Value);
}
MessageBox.Show(sum.ToString());
To calculate values from you datagridview, you can do several approaches
For example, you can retrieve by rows then reference the column of the cell by index or column name.
For example, adding values in "Column 3" would be:
var rows = dataGridView1.rows;
double sum = 0;
foreach (DataGridViewRow row in rows)
{
sum += (double)row.Cells["Column 3"].Value;
}
EDIT:
If you're using DataTable (which I presume from your comments) to get individual cell data, you can either reference the row first then adding an index based on the column, or you can create a temp row, then get the value using the column. The records or values within a DataTable are basically just collection of rows.
Example:
int col3 = workTable.Columns.IndexOf("Column 3") -1;
double amount = Convert.ToDouble(workTable.Rows[1][col3]); // 1st value in column 3
OR (extended for clarity)
DataRow row1 = workTable.Rows[1];
double amount = Convert.ToDouble(row1[col3]);
If you need to transpose values into a DataGridView, you can just set the DataSource property of a DataGridView instance i.e.
dataGridView1.DataSource = newFilledTable;

Sorting numeric column in datagridview

I am using a datagridview to show data in csv file. One of the column in datagridview in of numeric type [Column name: ID].
I am using autosort method of datagridview(sorting by clicking column header).
This works well for all the columns except this numeric column.
This column contains numbers 1 to 55
What I am getting now is after sorting is:
1,10,11,12,13,14,15,16,17,18,19,2,20,21,22,23,24,25,26,27,28,29,3,30,31...
...and so on. what I want is:
1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,...
Please help.
Thanks in advance.
You can use the event SortCompare like this:
private void dataGridView1_SortCompare(object sender, DataGridViewSortCompareEventArgs e) {
//Suppose your interested column has index 1
if (e.Column.Index == 1){
e.SortResult = int.Parse(e.CellValue1.ToString()).CompareTo(int.Parse(e.CellValue2.ToString()));
e.Handled = true;//pass by the default sorting
}
}
Build your DataTable:
DataTable dt = new DataTable();
dt.Columns.Add("ID", typeof(Int32));
dt.Columns.Add("Name");
dt.Columns.Add("ForeName");
I am using these columns due to the fact that I don't know what data you are storing.
After reading your csv-file you have to iterate through the data. Considering you have your data stored in a String array (String[][] arr) with the inner ArrayLength of 3 (ID, Name, ForeName).
for(int i=0;i<arr.Length;i++)
{
DataRow row = dt.NewRow();
row["ID"] = Convert.ToInt32(arr[i][0]);
row["Name"] = arr[i][1];
row["ForeName"] = arr[i][2];
dt.Rows.Add(row);
}
DataGridView dgv = new DataGridView();
dgv.DataSource = dt;
I hope this helps, it's a sample Code.
The reference to DataTable: https://msdn.microsoft.com/de-de/library/system.data.datatable(v=vs.110).aspx
EDIT
I just read that you already have a DataTable as result. You can build another DataTable as I did and iterate through your Data and convert the ID to an Integer. Please don't forget to set the Columns Type:
dt.Columns.Add("ID", typeof(Int32));
Well, your column is not numeric, but a text column that contains numeric string values. There's a huge difference! A real numeric column would apply numeric sorting, while your column uses alphanumeric sorting.
I'd try to actually change the underlying data type to int instead of string or apply manual sorting as suggested by lem2802.
Please add some information about how you fill the data grid view. Maybe that can help find an easier way than implementing a manual sort comparison.
According to your comment you create a DataTable as the data source for the grid view. You need to make sure that the column(s) containing numeric values also have a numeric type. In the code where you create the table and its columns, do something like this:
DataTable table = new DataTable();
table.Columns.Add("ID", typeof(Int32));
... // Other columns
Later when you create the rows based on the content of your CSV file, make sure to fill each row so that the value for the ID column actually is an int:
DataRow row = table.NewRow();
row["ID"] = Convert.ToInt32(idValueFromCSV);
... // Other columns
That way you'll get what you want without implementing custom sorting.

i want to pass value from another datatable

I am having one datatable to that table i want to pass value from another datatable.
for example:-
datatable1 in this
i want to pass value from
datatable2.row[0]["colname"]
i tried like :-
tblvdr.Rows[0]["item_Vendorname"] = dttemp.Rows[0]["item_Vendorname"];
error message:-
its showing error for No row at o position
DataRow tblvdrRow = tblvdr.NewRow();
tblvdrRow["item_Vendorname"]= dttemp.Rows[0]["item_Vendorname"];
tblvdr.Rows.Add(tblvdrRow);
It looks like your data table tblvrd does not have any row. For this use
DataRow newRow = tblvdr.NewRow();
One tme a new row is generated you can populate it from the row in another table. Naturally you need generate new row in tblvdr for every row in dttemp

Add data row to datatable at predefined index

I have a datatable with one column:
this.callsTable.Columns.Add("Call", typeof(String));
I then want to add a row to that datatable, but want to give a specific index, the commented number is the desired index:
this.callsTable.Rows.Add("Legs"); //11
Update:
Must be able to handle inputting hundreds of rows with unique
indexes.
The index must be what is defined by me no matter if there are enough
rows in the table or not for the insertat function.
You can use DataTable.Rows.InsertAt method.
DataRow dr = callsTable.NewRow(); //Create New Row
dr["Call"] = "Legs"; // Set Column Value
callsTable.Rows.InsertAt(dr, 11); // InsertAt specified position
See: DataRowCollection.InsertAt Method
If the value specified for the pos parameter is greater than the
number of rows in the collection, the new row is added to the end.

How can we copy the column data of one DataTable to another, even if there are different column names between DataTables?

I have two DataTables.
First is
DataTable NameAddressPhones = new DataTable();
with Three columns Name, Address and PhoneNo.But I only want two columns Name and Address data so I want to copy those columns (with data) to the new DataTable.
DataTable NameAddress = new DataTable();
For that I do
foreach (DataRow sourcerow in NameAddressPhones.Rows)
{
DataRow destRow = NameAddress.NewRow();
foreach (string colname in columns)
{
destRow[colname] = sourcerow[colname];
}
NameAddress.Rows.Add(destRow);
}
I clear the NameAddressPhones(first) DataTable every time there are new records inserted in the table. And every time there will be the same number of columns but the column names will be different like Nm instead of Name, Add instead of Address.Now the problem is the second DataTable already has column names Name and Address and now I want to copy the columns data of Nm and Add to the second DataTable but the column names are different than the column names of the second DataTable. So even if there are different column names I want to copy Nm column data of first DataTable to the column Name of second DataTable and column Add data of first DataTable to column Address of second DataTable.
In short how can we copy column data from one DataTable to another even if there are different column names of both DataTables like Nm is the column name of first DataTable and Name is the column name of second DataTable then the data of the column Nm should be copied to the column Name.
Here's the simplest way:
foreach (DataRow sourcerow in NameAdressPhones.Rows)
{
DataRow destRow = NameAdress.NewRow();
destRow["Name"] = sourcerow["Nm"];
destRow["Address"] = sourcerow["Add"];
NameAdress.Rows.Add(destRow);
}
Automation is great when it's available. When it's not, you have to map source columns to destination columns in some manner.
If the columns are in the same order in both tables, you could just reference the values by ordinal instead of column name, but that's such a bad idea I'm not even going to post any code for it.
Use column index number rather than names:
destRow[0] = sourcerow[0]; // for column 0 = "Name" or "NM"
If I've understood your question right, then the way this is usually done is by using stored procedures. You have the same stored procedures in both databases, but the implementation is specific to the table schema of each database. This allows you the abstraction you need.

Categories

Resources