Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I delete a column of a Dataset?

Tags:

c#

.net

dataset

How can I delete a column of a Dataset?

Is there a method that will do this for me like this:

rh.dsDetail = ds.Tables[0].Columns.Remove(

Or maybe like this:

rh.dsDetail = ds.Tables[0].Columns.Remove( ds.Tables[0].Columns[1],ds.Tables[0].Columns[2])
like image 418
ALEXALEXIYEV Avatar asked Nov 27 '22 16:11

ALEXALEXIYEV


2 Answers

First, a DataTable has columns, not a data-set.

If you want to get rid of them, then:

table.Columns.Clear();

otherwise, if you have the index:

table.Columns.RemoveAt(0);

should do the job if you have the column index. Note that if you remove column 0, then the numbers will shuffle (so you might need to do in reverse order).

Alternatively, you may want to remove by name:

table.Columns.Remove("Foo");
like image 114
Marc Gravell Avatar answered Dec 11 '22 07:12

Marc Gravell


I have done this before in both winforms & web apps. You must go thru the DataTable in reverse and then do an AcceptChanges at the end. This particular example is typical, in that it removes all the GUIDs (columns ending with "id").

    private void RemoveUselessFields(ref DataTable dtResults)
    {
        for (int i = dtResults.Columns.Count - 1; i >= 0; i--)
        {
            DataColumn column = dtResults.Columns[i];
            if (column.ColumnName.Substring(column.ColumnName.Length - 2, 2).ToUpper() == "ID") 
            {
                dtResults.Columns.Remove(column);
            }
        }
        dtResults.AcceptChanges();

    }
like image 26
pianocomposer Avatar answered Dec 11 '22 09:12

pianocomposer