How to remove empty values in a DataTable rows and merge - c#

I am trying to figure out a good way to remove empty values from rows and merge row2 to row1, row4 to row2 in a datatable.
DataTable with Empty rows to merge
---------------------
| Column1 | Column2 |
----------------------
ROW1 | XYZ | |
ROW2 | | ABC |
ROW3 | MNQ | |
ROW4 | | PQR |
Final datatable with merged rows
_____________________
| Column1 | Column2 |
----------------------
ROW1 | XYZ | ABC |
ROW2 | MNQ | PQR |
Can somebody help me accomplish this in C#?

Try to create two array that will store a column1 value and column2 value.
In loop go through all datatable rows and insert all not empty rows from column1 to array1 and rows from column2 to array2. Then on the end create new datatable that will have rows taked from array1 and array2.
For example in pseudocode.
var array1;
var array2;
for(var row in datatable)
{
if(row[column1] != null or empty)array1.push(row[column1].value);
if(row[column2] != null or empty)array2.push(row[column2].value);
}
and in the end (first check what array is biger).For example i assuming that array1 is bigger;
var newDatatable;
for(int i=0; i<array1.count; i++)
{
var row = new row;
newDatatable.row[column1].addRowValue(array1[i])
if(array2.count < i){
newDatatable.row[column2].addRowValue(array2[i])
}
}

Related

Copy row from datatable to another where there are common column headers

I have two datatables, I am trying to copy row from one table to another, I have tried this. the thing is that my tables are not exactly the same, both tables have common headers, but to the second table have more columns, therefore I need "smart" copy, i.e to copy the row according to the column header name.
d1:
+--------+--------+--------+
| ID | aaa | bbb |
+--------+--------+--------+
| 23 | value1 | value2 | <----copy this row
d2:
+--------+--------+--------+--------+
| ID | ccc | bbb | aaa |
+--------+--------+--------+--------+
| 23 | | value2 | value1 | <----I need this result
but this code:
string rowID=23;
DataRow[] result = dt1.Select($"ID = {rowID}");
dt2.Rows.Add(result[0].ItemArray);
gives:
d2:
+--------+--------+--------+--------+
| ID | ccc | bbb | aaa |
+--------+--------+--------+--------+
| 23 | value1 | value2 | | <---- :( NOT what I need
I think this is your homework, but here you have some simple and not very smart solution:
private DataTable DTCopySample()
{
int cnt = 0;
DataTable dt1 = new DataTable();
dt1.Columns.Add("ID");
dt1.Columns.Add("aaa");
dt1.Columns.Add("bbb");
DataTable dt2 = new DataTable();
dt2.Columns.Add("ID");
dt2.Columns.Add("ccc");
dt2.Columns.Add("bbb");
dt2.Columns.Add("aaa");
dt1.Rows.Add();
dt1.Rows[0]["ID"] = "23";
dt1.Rows[0]["aaa"] = "val1";
dt1.Rows[0]["bbb"] = "val2";
dt1.Rows.Add();
dt1.Rows[1]["ID"] = "99";
dt1.Rows[1]["aaa"] = "val99";
dt1.Rows[1]["bbb"] = "val98";
string colName = string.Empty;
foreach (DataRow row in dt1.Rows)
{
dt2.Rows.Add();
foreach (DataColumn col in dt1.Columns)
{
dt2.Rows[cnt][col.ColumnName] = row[col.ColumnName].ToString();
}
cnt++;
}
return dt2;
}
There are more smart and better solutions, but this is fast-written (2 mins) and works.
Remeber, that you have not specified columns datatypes or anything else, so I assumed there are strings everywhere for creating simple sample.

Adjust gridview rowIndex when programmatically adding new row

I've seen this article http://asp.net-informations.com/gridview/newrow.htm and this post http://forums.asp.net/p/1534978/3725419.aspx#3725419 and I've done it for have that separator row collapsible with jquery and it's working great in display mode. The problems occuring when try to do something else with gridview, because there's a weird behaviour.. I've add a simple button that have just to set a radiobutton that's in every gridview row (except in the new added GroupHeaders rows). Then if I have added two new row he is skipping setting the last two rows in the GridView..
public void AddNewRow(object sender, GridViewRowEventArgs e)
{
GridView GridView1 = (GridView)sender;
GridViewRow NewTotalRow = new GridViewRow(-1, -1, DataControlRowType.Header, DataControlRowState.Normal);
TableCell HeaderCell = new TableCell();
HeaderCell.Attributes.Add("onclick", "collapsible('" + rowgroup + "')");
NewTotalRow.Cells.Add(HeaderCell);
TableCell HeaderCellIndex = new TableCell();
int indexCorrente = e.Row.RowIndex + index;
HeaderCellIndex.Text = indexCorrente.ToString();
NewTotalRow.Cells.Add(HeaderCellIndex);
GridView1.Controls[0].Controls.Add(NewTotalRow);
}
protected void gdDettaglio_RowCreated(object sender, GridViewRowEventArgs e)
{
bool newRow = false;
if ((DataBinder.Eval(e.Row.DataItem, "Stato") != null))
{
if (statoCorrente != Convert.ToInt32(DataBinder.Eval(e.Row.DataItem, "Stato").ToString()))
newRow = true;
}
if (newRow)
{
AddNewRow(sender, e);
}
}
Printing the row index (just to check it) next to each row I'm displaying this situation (with two GroupHeader rows added):
(The index are as they are printing them in gdDettaglio_RowCreated for GroupHeadrs rows and on gdDettaglio_OnDataBound for the other rows)
-----------------------------------------
| HEADER |
|---------------------------------------|
-----------------------------------------
| Gruppo 1 | index -1 |
|---------------------------------------|
| grp1 | x | blablabla | | index 0 |
| grp1 | y | blablabla | | index 1 |
| grp1 | z | blablabla | | index 2 |
| grp1 | x | blablabla | | index 3 |
| grp1 | x | blablabla | | index 4 |
|---------------------------------------|
| Gruppo 2 | index -1 |
|---------------------------------------|
| grp2 | x | blablabla | | index 5 |
| grp2 | y | blablabla | | index 6 |
| grp2 | z | blablabla | | index 7 |
| grp2 | z | blablabla | | index 8 |
| grp2 | z | blablabla | | index 9 |
| grp2 | z | blablabla | | index 10 |
-----------------------------------------
in the button code I've just:
foreach (GridViewRow riga in gdDettaglio.Rows)
{
if (riga.RowType == DataControlRowType.DataRow)
{
RadioButtonList rad = (RadioButtonList)riga.FindControl("rad");
rad.SelectedValue = "True";
}
}
UPDATE:
Doing the same thing on jquery work, it affects all the row:
function accettaTutte() {
$("#<%=gdDettaglio.ClientID%> tr:has(td)").each(function () {
var items = $(this).find("[id$='radDaPa'] input:radio'");
for (var i = 0; i < items.length; i++) {
if (items[i].value == 'True') {
if (!(items[i].checked)) {
items[i].checked = true;
}
break;
}
}
});
return false;
}
But I still need to do a foreach on that gridview, to update db, some idea on what could try to do? On every row I've also a "single row save" ImageButton, but clicking on it on the last two rows it's not firing the RowCommand event... It's like the two added GroupHeader rows are pushing out the last two data rows, no matter about the index.. If I click the ImageButton on the row with displayed (using Text='<%#Container.DataItemIndex%>') rowIndex 2, in the rowCommand it become rowIndex 3, but it modified the right row, the one I've clicked.. If i do the same on row 7, it become 9.. But if forced it to get value on rowIndex 11, U'm getting ArgumentOutOfRangeException, because Rows.Count It's still 11..
OK, now I am adding to the list that is GridView DataSource as many empty elements as are the GroupHeaders rows, so GridView.Rows.Count is enough to get all the rows..

Check occurrence of word appearing in datatable column

I have the data below in a datatable this is example data. I would like get the occurrence of 12,13 in the datatable as normally there would be 10-20 million row in the datatable.
Customer | quantity | Product | Code
1 | 3 | Product | 12
2 | 4 | Product | 13
3 | 1 | Product | 12
4 | 6 | Product | 13
how about simple for each loop
private int getCount(int yourSearchDigit)
{
int counter = 0;
foreach (DataRow dr in youDataTable.Rows)
{
if (Convert.ToInt32(dr["Code"]) == yourSearchDigit)
counter++;
}
return counter;
}
You can use Linq-To-DataTable:
int[] allowedCodes = new []{ 12, 13 };
var rows = table.AsEnumerable()
.Where(r => allowedCodes.Contains(r.Field<int>("Code")));
However, if you have 10-20 million row in the datatable you should consider to do the filtering in the database itself.
If you want to know the number they occur:
int count = table.AsEnumerable()
.Count(r => allowedCodes.Contains(r.Field<int>("Code")));

How to select rows from DataTable based on Index / Row Number?

I have a DataTable. I want to select the rows based on the Index/Row Number of the rows in DataTable.
Suppose below is the DataTable:
---------------- ---------------
| ID | Name | | Index/RowNo |
---------------- ---------------
| A001 | John | | 1 |
| A002 | Foo | | 2 |
| A003 | Rambo | | 3 |
| A004 | Andy | | 4 |
| ... | ... | | 5 |
---------------- ---------------
Now, i want to select the Rows from above shown DataTable using criteria say for example Index > 2, In that case First entry at Index 1, A001 | John, will not become part of the resultant DataTable. How can i do it efficiently?
Moreover, i want to have my result both in the form of DataTable and Linq query outcome.
I am trying to do something like this:
var result = dt.Select("RowNum > 1", "");
OR
var result = from row in dt.AsEnumerable()
where RowNum > 1
select row;
I am trying to do something like this:
var result = dt.Select("RowNum > 1", "");
You can use Enumerable.Skip even with a DataTable since it is an IEnumerable<DataRow>:
IEnumerable<DataRow> allButFirst = table.AsEnumerable().Skip(1);
get a new DataTable with:
DataTable tblAllButFirst = allButFirst.CopyToDataTable();
If your next question is how you can take only rows with given indices:
var allowedIndices = new[]{ 2, 4, 7, 8, 9, 10 };
DataTable tblAllowedRows = table.AsEnumerable()
.Where((r, i) => allowedIndices.Contains(i))
.CopyToDataTable();
var result = table.AsEnumerable()
.Where((row, index) => index > 1)
.CopyToDataTable()

How to learn and show gridview rows includes "?" data

There is a gridview which includes 6 columns. I bound the data to some columns. For example, 3 and 5 th columns have data.
I want to show There is 2 data in first columns if there is 3 data in separate columns I want to write 3 in the first column.
Column1 | Column2 | Column3 | Column4 | Column5 | Column6
2 | | stack | | overflow |
4 | sta | ck | over | flow |
1 | | | | | stcvrflw
How can I do it?
I populate the grid
e.Row.Cells[i].Text = html;
and html variable includes < table>.... some values come from db.
After you populate the grid:
for (int i = 0; i < gv.Rows.Count; i++)
{
valueCount=0;
for (int j = 1; j < gv.Columns.Count; j++)
{
if (gv.Rows[i].Cells[j].ToString()!="")
valueCount++;
}
gv.Rows[i].Cells[0].Text =valueCount.ToString();
}

Categories

Resources