how to add a column/row at the defined position...

Posted by Santosh4u under VB.NET on 6/6/2011 | Points: 10 | Views : 62347 | Status : [Member] | Replies : 3
hi

can anybody plz tell me,how to add a column/row at the defined position...

Ex: let say i have a datatable contains 10 columns stating from id,name etc..
but i wnat to add a new empty column as (slno) before the the id column and not the datatable will be slno.id,name etc.......


same like row i want add some null row from index 0 ....



regards
santosh




Responses

Posted by: Ndebata on: 6/6/2011 [Member] Starter | Points: 25

Up
0
Down
Hi
For inserting row at a particular postion there exists a method in DataTable.Rows, but incase of columns no such methods exists.
Please take a look at the sample Code bellow.
//Sample Table

DataTable dtSource = new DataTable();
dtSource.Columns.Add("Column1");
dtSource.Columns.Add("Column2");
dtSource.Columns.Add("Column3");
dtSource.Rows.Add(new object[] { "Test1", "Test2", "Test3" });

//Insert Row at a position
DataRow drnewrow = dtSource.NewRow();
drnewrow.ItemArray = new object[] { "Row0Test1", "Row0Test2", "Row0Test3" };
dtSource.Rows.InsertAt(drnewrow, 0);

//Insert Column at a position
//Pls refer the method bellow.
dtSource=dtSource.InserColumnAt(0, new DataColumn("Hello"));
//Similarly insert a new column at postion 2
dtSource = dtSource.InserColumnAt(2, new DataColumn("WorldAtNumber2"));

The extension method is created so that it will apply to all datatable.

public static class MyExtn
{
public static DataTable InserColumnAt(this DataTable dtSource, int postion, DataColumn NewColumn)
{
if (postion > dtSource.Columns.Count || postion < 0)
throw new InvalidDataException("Not Valid Position");
DataColumn[] colarr = new DataColumn[dtSource.Columns.Count];
dtSource.Columns.CopyTo(colarr, 0);
DataTable dt = new DataTable();
bool added = false;
for (int i = 0; i <= colarr.Length; i++)
{
if (!added && i == postion)
{
dt.Columns.Add(NewColumn);
added = true;
i--;
}
else if (i < colarr.Length)
dt.Columns.Add(colarr[i].ColumnName);
}
foreach (DataRow item in dtSource.Rows)
{
List<object> objlist = new List<object>();
foreach (DataColumn colitem in dt.Columns)
{
if (colarr.ToList().FindIndex(a => a.ColumnName.Equals(colitem.ColumnName)) != -1)
{
objlist.Add(item[colitem.ColumnName]);
}
else
{
objlist.Add(null);
}
}
dt.Rows.Add(objlist.ToArray());
}
return dt;
}
}


Thanks,
Debata

Santosh4u, if this helps please login to Mark As Answer. | Alert Moderator

Posted by: Vforvijay on: 6/6/2011 [Member] Starter | Points: 25

Up
0
Down
hi,...check out this link it may helpful to u
http://vbdotnetaddict.blogspot.com/2011/03/how-to-insert-new-row-in-datatable-in.html

Santosh4u, if this helps please login to Mark As Answer. | Alert Moderator

Login to post response