C# - Add Empty Column to DataTable - c#

I am creating an Excel using DataTable. My requirement is to skip first two columns and populate values from third column. When I try to add column with string.Empty, it creates Column1,Column2 in Excel.
As per link https://learn.microsoft.com/en-us/dotnet/framework/data/adonet/dataset-datatable-dataview/adding-columns-to-a-datatable , it auto generates Column1. But somehow I need to skip first two Columns.
Can someone help me to achieve this.
var myDataSet = new DataSet();
var table = myDataSet.Tables.Add("ProductDetails");
table.Columns.Add(string.Empty);
table.Columns.Add(string.Empty);
table.Columns.Add("ID");
table.Columns.Add("Name");
table.Columns.Add("Code");
table.Columns.Add("Price");
Current output in Excel:
Expected output:

Related

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

how to add new datatable to dataset at first position

i have one dataset with 3 data tables again i have to add one more data table in same dataset at first position(Ex:mydataset.tables[0]th position) .can any one help me regarding this.
You will probably need to pull all the datatables out of the dataset into a list, get them in the right order, and then re-add them all to the dataset since you cannot insert to or modify the existing order:
var tables = new DataTable[4];
tables[0] = mynewtable;
tables[1] = mydataset.Tables[0];
tables[2] = mydataset.Tables[1];
tables[3] = mydataset.Tables[2];
mydataset.Tables.Clear();
mydataset.Tables.Add(Tables[0]);
mydataset.Tables.Add(Tables[1]);
mydataset.Tables.Add(Tables[2]);
mydataset.Tables.Add(Tables[3]);

How to add datarows to an already existing datatable?

I am having an datatable which is already populated. Now i want to add few rows to that datatable ,but some of rows might already exist in the datatable.I know its unneccesary but tht is the requirement.
I tried couple of things and got "the row already exist in this table : & this row belongs to some other table" .I also tried importRow ,but i guess it avoid the duplicates by dafault.
Is there any way to do that .If the datatable has 7 rows and i want to add 3 more rows whether its already exist or not. My goal is to send 10 rows to the calling function .
Or is there any other approach altogether?
UPDATE
Using
rowsToAdd.CopyToDataTable(dsCount.Tables[2], LoadOption.PreserveChanges); works but I'm not sure it's the proper way.
You can add new rows in DataTable using code below
DataRow newRow = dataTable.NewRow();
dataTable.Rows.Add(newRow);
To check for any duplicates try
if (table.Rows.Contain(PriKeyTypeValue)) /*See if a Primary Key Value is in
the table already */
continue;
else
table.Row.Add(value1, value2, value3);
If you want to be able to insert duplicate rows but do not want to have an exception thrown set-up your primary key as a unique self-incrementing int then you can insert as many duplicates as you feel like without having to check to see if the table contains that value. Just make sure that it would suffice to have duplicates. There are plenty of examples of setting a primary key just search for it (msdn has at least one). Here is an example:
DataTable table = new DataTable();
table.Columns.Add("Column", typeof(int));
DataColumn column = table.Columns["Column"];
column.Unique = true;
column.AutoIncrement = true;
column.AutoIncrementStep = 1; //change these to whatever works for you
column.AutoIncrementSeed = 1;
table.PrimaryKey = new DataColumn[] { column };
Create a new row using the NewRow() function.
var dataTable = new DataTable();
var dataRow = dataTable.NewRow();
Then add your new row to your datatable
dataTable.Rows.Add(dataRow)
I believe you can use the NewRow() function of the DataTable if you're simply appending a row to the table.
DataTable table = new DataTable();
DataRow row = table.NewRow();
table.Rows.Add(row);
Will that not suffice?
The most straightforward method. After spending a few hours trying everything else.
DataRow dr = ds.Tables[0].NewRow();
dr["ColumnName1"] = "columnvalue"; //string
dr["ColumnName2"] = 123 //int
ds.Tables[0].Rows.Add(dr);

asp.net copying row from one datatable to another

i have a datable and like this i have searched a datarow from the datable on the basis of some primary now i want to add that searched row to another datatable how can i achieve this please let me know
DataTable findRows = (DataTable)ViewState["dt"];
List<int> selectedList=(List<int>)ViewState["selectedList"];
DataTable temp = new DataTable();
foreach (int id in selectedList)
{
DataRow dr=findRows.Rows.Find(id);
}
now i want it to add to datatable temp how can i achieve this?
First, when creating temp don't just instantiate it as a new DataTable but instead call .Clone() on findrows to create a structurally identical DataTable.
Second, use .ImportRow() on the second DataTable and pass it the row from the first DataTable that you'd like to copy. This should create an entirely new row in the second table with the same values as the row from the first table.

Categories

Resources