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

前提是你 提交于 2019-12-11 06:27:37

问题


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?


回答1:


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!




回答2:


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.



来源:https://stackoverflow.com/questions/12385599/how-to-dynamically-hide-fields-in-a-detailsview-fields-count-is-always-0

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!