bgs264
bgs264

Reputation: 4642

How to dynamically hide fields in a DetailsView (fields count is always 0)

I am using a DetailsView to show the details of a single row from a DataTable.

I do not know the column names at design time, so I have AutoGenerateRows = true in the markup.

DataView dv = myDataTable.AsDataView();
dv.RowFilter = string.Format("ResourceID = {0}", resourceId);

dvScoresBreakdown.DataSource = dv;
dvScoresBreakdown.DataBind();

There are about 4 columns in the DataView which I don't want the DetailsView to display - mainly ID columns.

I understand that I should access the Fields property of the DataView and set the relevant fields invisible:

dvScoresBreakdown.Fields[0].Visible = false;
dvScoresBreakdown.Fields[1].Visible = false;

However, the .Fields.Count is always zero. So I get an index out of bounds exception.

When I say "always zero", I mean it's zero right after the .DataBind(), and also in the OnDataBinding, OnDataBound, and OnPreRender events.

But, the DetailsView does render on the page and show everything - all the columns in the original DataView - so the dataview is binding!

What am I doing wrong?

Upvotes: 2

Views: 5640

Answers (2)

bgs264
bgs264

Reputation: 4642

I've just found out, the way to do it is to remove rows right after the .DataBind() method.

dvScoresBreakdown.DataSource = dv;
dvScoresBreakdown.DataBind();

dvScoresBreakdown.Rows[0].Visible = false;
dvScoresBreakdown.Rows[1].Visible = false;

Hope this can help someone else!

Upvotes: 5

imran
imran

Reputation: 66

The Columns collection only stores the explicitly declared columns, so if you’re using autogenerated columns, the count will be zero. If you’re using autogenerated column, after databind you could loop through the rows collection and make the appropriate cells invisible, like:

If dvScoresBreakdown is GridView

 dvScoresBreakdown .DataBind();
if (dvScoresBreakdown .Columns.Count > 0)
    dvScoresBreakdown .Columns[0].Visible = false;
else
{
    dvScoresBreakdown .HeaderRow.Cells[0].Visible = false;
    foreach (GridViewRow gvr in dvScoresBreakdown .Rows)
    {
        gvr.Cells[0].Visible = false;
    }
}

I think this will help you.

Upvotes: -1

Related Questions