Question

I'm using a list of objects as the data source of my GridView and when I set columns to not be visible the updates fail because the value of those columns is changed to null (and the column doesn't allow nulls). The values do exist when the columns are visible but I really don't want to display these columns because, for the most part, they are ID columns that the user doesn't really need to see.

EDIT: I've tried the hidden field option but it still sets the value to null. I've looked at the page source and the hidden field exists with the appropriate value...

Was it helpful?

Solution

I found this solution to simulate hidden columns in .Net 2.0:

Implement the GridView.RowCreated event.

protected void GridView1_RowCreated(object sender, GridViewRowEventArgs e)
{
    e.Row.Cells[1].Visible = false;
    e.Row.Cells[2].Visible = false;
}

Here's the link: http://www.beansoftware.com/ASP.NET-Tutorials/GridView-Hidden-Column.aspx

I guess in 2.0 when a column is not visible the databinding fails for that column but this method hides after the link has been established so it tricks the system (?).

OTHER TIPS

Microsoft recommends using the DataKeyNames property of the GridView control.

Instead of using code-behind to hide certain columns, you can just remove the bound fields from the GridView and specify them in the DataKeyNames property:

<asp:GridView ID="GridView1" runat="server" 
        DataKeyNames="SalesOrderID,SalesOrderDetailID"
        DataSourceID="LinqDataSource1">

This way the fields will not show to the user but the GridView knows to keep the values around for updating, etc.

If you aren't doing so already, I'd consider using Template columns for your data and do "manual" data binding (either "inline" or in the code behind page using the RowDataBound event). That way you can test for DBNull and simply ignore putting a value in the column if the value is NULL. This will also allow for the columns to be properly hid.

You could do it with hidden fields for the values you don't want to display. that way you can still use the same databinding and other functions as you do today.

When a field inside GridView is made invisible, its cell values are not more accessible or these are null or empty.

In order to solve this issue, you just have to assign column names (Hidden Fields) to DataKeyNames property of GridView by doing DataKeyNames="colName1,colName2,colName3".

Then access their cell values as cellValue = GridView1.DataKeys[0]["ID"].ToString();

I have written a simple post demonstrating the solution to your problem at here.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top