datatable select the columns we want dynamically - c#

I have a datatable with almost 20 columns in it. in another DT i get only the columns I want. Recently my requirements have changed i.e. Firstly the number of columns in the original DT were constant but now it increases or decreases depending upon the data.
So now, if I statically provide the column names I need in my new DT it isnt of much use to me.
Is there any way in which I can include those columns which may or may not be in the Original Datatable????
For eg: col1|col2|col3|.......col20.
The columns that may bve present or absent fall between col12 and col 16. Is there anyway in which I could make it work????
EDIT:
I want col1,col2,col3 and all columns aftr col12...can I do it???

You can have total number of columns from datatable using
DataTable.Columns.Count
So you will know how many columns are there and you will know which column is in datatable and which is not.

Related

ArgumentException when adding rows from DataGridView to DataTable

I'm fairly new to C# programming. I want to take user input from DataGridView to a DataTable. However, I get ArgumentException from this code
DataTable dd=new DataTable();
foreach (DataGridViewRow dr in dataGridView1.Rows)
{
dd.Rows.Add(dr);
}
Is there any way I can do to fix it? I'd like to have alternatives to get input from dataGridView1 as well.
edit: forgot to mention, dataGridView1 has one comboBox column.
edit2: the error read "Input array is longer than the number of columns in this table."
Input array is longer than the number of columns in this table.
You have to add a column to DataTable eg: dd.Columns.Add("SomeColumnName"), before you add rows to it.
However, if there's no particular requirement to use DataTable then you should use, for example, List to store the rows. It is a much simpler data structure.
var listOfRows = gridView.Rows.Cast<DataGridViewRow>().ToList();

C# DataTable: Get most frequent value for every column

I want to get the most frequent value for every column in my DataTable.
I found an answer to a similar question for a Table, but it does not seem to work for my DataTable.
Actually I would welcome a list of distinct values for every column.

How to avoid adding duplicate rows to a datatable

I'm using a SqlDataReader to add row by row into a datatable like follows:
while (reader.Read())
{
dataTable.LoadDataRow(reader.CurrentRow(), LoadOption.PreserveChanges);
}
This works, but I need to be able to avoid adding duplicate rows to the dataTable. I would love to be able to use the Contains or Find methods from the dataTable, but I can't find a way to turn the object[] from reader.CurrentRow() into a DataRow to compare to without adding it to a datatable.
I've looked into the option of making a hashset of the object[]s, and then adding them all at once to the datatable at the end, but I forgot that the default object IEqualityComparer only compares the reference.
Is there a feasible way of doing this without removing the duplicates at the end?
If removing the duplicates is the only way to go, what is the best way to do that?
EDIT:
I'm splitting distinct rows from the database into separate datatables in code. Each row from the query result is distinct, but sections of each row are not. Unfortunately I need to do exactly what my question is asking, as the results from the query are already distinct.
You didn't provide a ton of detail, but I hope this is comprehensive.
If you need a single column to be unique, then in your Columns collection in your datatable, specify the column like this:
DataTable appeals = new DataTable("Appeals");
appeals.Columns["PriorAppealNumber"].Unique = true;
DataColumn keyField = new DataColumn("AppealNumber", typeof(string));
appeals.Columns.Add(keyField);
If the uniqueness needs to span multiple rows, this is the method:
var myUniqueConstraint = new UniqueConstraint( new DataColumn[] {appeals.Columns[0], appeals.Columns[1], appeals.Columns[2]} );
appeals.Constraints.Add(myUniqueConstraint);
That will enforce the constraints BEFORE you try to commit back to the source database.
The easiest way is to actually make sure there are no duplicate rows at all - if you're querying relational database use DISTINCT - that will return only unique rows.

Multiplying columns in a datatable

I have a datatable in C# with a "price" column and an "allocation" column, and I need to multiply the price column by the allocation column and put the result in the price column. Is there a way to do with without looping over the table? I have tried something like this:
DataTable dt = getData();
dt.Columns["Price"].Expression = "Allocation * Price";
But obviously this gives me the following exception:
Cannot set Expression property due to circular reference in the expression.
Does anyone know of another way to accomplish this? Thanks beforehand.
You could use a LINQ expression to do it in one line:
dt.Rows.ForEach(x => x["Price"] = (double)x["Price"] * (double)x["Allocation"]);
You could just add another column to the DataTable:
dt.Columns.Add("TotalPrice", typeof(decimal));
dt["TotalPrice"] = "Allocation * Price";
Add a new column whose value is calculated from the other two:
dt.Columns.Add("TotalPrice", typeof(decimal), "Allocation * Price");
With this approach, the TotalPrice will always be up to date if you change the Price or Allocation
If you don't have a seperate column, what happens when something makes the calculation execute again....
At some point the amount of code you have to add bend datatable to do what you want (without introducing a mass of potential 'erm features) will be more effort than just knocking up a class to hold the stuff.
Read from datatable write from databale isn't hard, nor is binding to a list of thingies.

DataView Sort - how to when column names are unknown

I need advice on how to go about a problem I have with sorting a DataView in C#.
I need to add a sort property to my DataView because I later need it when I call a Find on the DataView (which needs to have a sort property specified in order to work). I need the Find in order to properly map a DataRow to a DataGridViewRow. I currently just use the row index to map to the DataGridViewRow, but this won't work in all cases if the user physically moves rows, or changes the sort order in the DataGridView (UI) because then the ids no longer match-up/map.
When I create the DataView, I load in a DataTable to pass in for creation. This DataTable can be of any form, I do not know what the DataTable contains for columns and rows. Therefore, I cannot create a sort if I don't know any column names to sort by.
I was thinking of just taking the first column name (column[0]) - no matter what it is and using that to sort. But this seems kinda sketchy, no?
My question is, is there a better way to determine what to sort my DataView by when column names are unknown?
Thanks!
I haven't tried it, but since it sorts based on the column name you pass in, couldn't you sort based on index with something like:
dataview.Sort = dataview.Table.Columns[index].ColumnName + " DESC";

Categories

Resources