Hi sureshMGR,
You might need to remove more than one column then you should iterate backwards through the collection using a for statement.
This is because each time you delete a column it alters the indices of the column still to be examined which all move down one. If you iterate forwards you will therefore fail to examine the next element in the collection.
You can still iterate forwards if you decrement the loop control variable before the next iteration.
Refer below code.
Code
C#
protected void Page_Load(object sender, EventArgs e)
{
if (!this.IsPostBack)
{
DataSet _dataSet = new DataSet();
DataTable dt = new DataTable();
dt.Columns.AddRange(new DataColumn[] { new DataColumn("Id", typeof(int)), new DataColumn("Id1", typeof(string)), new DataColumn("Country", typeof(string)) });
dt.Rows.Add(1, "Mudassar Khan", "India");
dt.Rows.Add(2, "John Hammod", "USA");
_dataSet.Tables.Add(dt);
for (int i = 0; i < _dataSet.Tables[0].Columns.Count; i++)
{
string test = _dataSet.Tables[0].Columns[i].ColumnName;
if (test.Contains("Id"))
{
_dataSet.Tables[0].Columns.Remove(test);
i = i - 1;
}
}
}
}
VB.Net
Protected Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs) Handles Me.Load
If Not Me.IsPostBack Then
Dim _dataSet As DataSet = New DataSet()
Dim dt As DataTable = New DataTable()
dt.Columns.AddRange(New DataColumn() {New DataColumn("Id", GetType(Integer)), New DataColumn("Id1", GetType(String)), New DataColumn("Country", GetType(String))})
dt.Rows.Add(1, "Mudassar Khan", "India")
dt.Rows.Add(2, "John Hammod", "USA")
_dataSet.Tables.Add(dt)
For i As Integer = 0 To _dataSet.Tables(0).Columns.Count - 1
Dim test As String = _dataSet.Tables(0).Columns(i).ColumnName
If test.Contains("Id") Then
_dataSet.Tables(0).Columns.Remove(test)
i = i - 1
End If
Next
End If
End Sub