ASP.NET: GridView value set to null if column is not visible

I am using a list of objects as the data source of my GridView, and when I set the columns so that they are not visible, the updates fail because the value of those columns changes to zero (and the column does not allow zeros). Values โ€‹โ€‹exist when the columns are visible. but I really don't want to display those columns because they are mostly ID columns that the user really doesn't need to see.

EDIT: I tried the hidden field option, but it sets it to null anyway. I looked at the source of the page and the hidden field exists with the corresponding value ...

+1


source to share


5 answers


I found this solution for modeling 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 think in 2.0, when the column is not visible, the data binding is not valid for that column, but this method is hidden after the link has been set, so it cheats the system (?).

+3


source


Microsoft recommends using the DataKeyNames property of the GridView control.

Instead of using code to hide specific columns, you can simply remove the associated 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 be visible to the user, but the GridView knows how to store the values โ€‹โ€‹to update, etc.

+1


source


If you don't, I would consider using template columns for your data and doing "manual" data binding (either "inline" or in code by page using the RowDataBound event). This way you can test DBNull and just ignore setting the value on the column if the value is NULL. This will also allow the columns to be hidden correctly.

0


source


You can do this with hidden fields for values โ€‹โ€‹that you do not want to display. this way you can still use the same data binding and other functionality as you do today.

0


source


When a field inside the GridView becomes invisible, its cell values โ€‹โ€‹are no longer available or they are empty or empty.

To solve this problem, you just need to assign the column names (hidden fields) to the DataKeyNames property of the GridView by doing DataKeyNames="colName1,colName2,colName3"

.

Then access the values โ€‹โ€‹of their cells as cellValue = GridView1.DataKeys[0]["ID"].ToString();

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

0


source







All Articles