ASP.NET DEMO 7: 解决无法获取 GridView 隐藏列值问题

在 GridView/DetailsView 中如果 BoundField 的 Visible=false 时,  回发的时候无法此列的值(GridViewRow.Cells[cellIndex].Text将为空),网上很多朋友提出了各种各样的解决方案,这里整理一下,并提供示例。

未反射 GridView 类,不曾仔细阅读其源码,不知内部实现对于 BoundField(普通绑定列),当此列 Visible=false 时,是未执行绑定计算,还是未保持 ViewState,也许这是就是传说的GridView性能由于DataGrid的一点吧。事实上,这样反而给粗心的开发者带来了“莫名其妙”的问题。DataGrid 中 BoundColumn 不存在此问题。

MSDN 对此是这样的说明:

None.gif 备注
None.gif
None.gif使用 Visible 属性显示或隐藏数据绑定控件中的 DataControlField 对象。
None.gif
None.gif如果 Visible 属性为 false,则不显示数据值并且不做到客户端的往返行程。如果要往返不可见字段的数据,请将字段名添加到数据绑定控件的 DataKeyNames 属性。
http://msdn2.microsoft.com/zh-cn/library/system.web.ui.webcontrols.datacontrolfield.visible(VS.80).aspx
说明:BoundField 类继承自 DataControlField 类。

事实上,实际项目中,我几乎没有使用隐藏列的经验,即使在 1.x 的 DataGrid 中,为了记录某些有用的隐藏信息,我一般使用模板列中嵌套控件,如label 并设置其visible=false 最佳当然是用 input type=hidden runat=server(注:1.x 中没有 asp:hiddenfield 控件)。
而 2.0 ,最佳的方案,当然是使用 DataKeys 来存储,不像DataGrid.DataKey ,GridView/DetailsView.DataKeys 可以存储多个值。

以下为示例代码,代码包含各种方案的“自说明”注释,不再做过多的解释。

ContractedBlock.gif ExpandedBlockStart.gif
ExpandedBlockStart.gifContractedBlock.gif<%dot.gif@ Page Language="C#" %>
ExpandedBlockStart.gifContractedBlock.gif
<%dot.gif@ Import Namespace="System.Data" %>
None.gif
ExpandedBlockStart.gifContractedBlock.gif
<%dot.gif--http://community.csdn.net/Expert/TopicView3.asp?id=5646507--%>
None.gif
None.gif
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
None.gif
ExpandedBlockStart.gifContractedBlock.gif
<script runat="server">dot.gif
InBlock.gif
InBlock.gif    protected 
void Page_Load(object sender, EventArgs e)
ExpandedSubBlockStart.gifContractedSubBlock.gif    
dot.gif{
ExpandedSubBlockStart.gifContractedSubBlock.gif        
if (!IsPostBack) dot.gif{
InBlock.gif            LoadProductData();
ExpandedSubBlockEnd.gif        }

ExpandedSubBlockEnd.gif    }
  
InBlock.gif
InBlock.gif    protected 
void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
ExpandedSubBlockStart.gifContractedSubBlock.gif    
dot.gif{
InBlock.gif        
// 客户端 CSS 控制隐藏,不安全,毕竟数据还是呈现到客户端了
InBlock.gif
        e.Row.Cells[3].Style.Add(HtmlTextWriterStyle.Display, "none");
InBlock.gif        
// 设置单元格隐藏, TableCell.Visible=false, OK
InBlock.gif
        e.Row.Cells[4].Visible = false;
ExpandedSubBlockEnd.gif    }

InBlock.gif    
InBlock.gif    protected 
void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
ExpandedSubBlockStart.gifContractedSubBlock.gif    
dot.gif{        
InBlock.gif        
int rowIndex = -1;        
ExpandedSubBlockStart.gifContractedSubBlock.gif        
switch (e.CommandName) dot.gif{
InBlock.gif            
case "Select":
InBlock.gif                rowIndex 
= Convert.ToInt32(e.CommandArgument);
InBlock.gif                GridViewRow row 
= GridView1.Rows[rowIndex];
InBlock.gif                Response.Write(String.Format(
"<pre style='color:red'>您选择了第 {0} 行\n当前行 ProductId={1}, CategoryId={2}(两者均由DataKeys获取)\n"
InBlock.gif                    (row.RowIndex 
+ 1),
InBlock.gif                    GridView1.DataKeys[rowIndex].Values[
"ProductId"],
InBlock.gif                    GridView1.DataKeys[rowIndex].Values[
"CategoryId"]));                
ExpandedSubBlockStart.gifContractedSubBlock.gif                
for (int columnIndex=0; columnIndex< GridView1.Columns.Count; columnIndex++dot.gif{
InBlock.gif                    DataControlField field 
= GridView1.Columns[columnIndex];
InBlock.gif                    string text 
= null;
ExpandedSubBlockStart.gifContractedSubBlock.gif                    
if (field is BoundField) dot.gif{
InBlock.gif                        text 
= row.Cells[columnIndex].Text;
ExpandedSubBlockEnd.gif                    }

ExpandedSubBlockStart.gifContractedSubBlock.gif                    
else if (field is TemplateField) dot.gif{
InBlock.gif                        Label lbl 
= row.Cells[columnIndex].FindControl("lblProductID") as Label;
ExpandedSubBlockStart.gifContractedSubBlock.gif                        
if (lbl != nulldot.gif{
InBlock.gif                            text 
= lbl.Text;
ExpandedSubBlockEnd.gif                        }

ExpandedSubBlockStart.gifContractedSubBlock.gif                        
else dot.gif{
InBlock.gif                            text 
= row.Cells[columnIndex].Text;
ExpandedSubBlockEnd.gif                        }

ExpandedSubBlockEnd.gif                    }

InBlock.gif                    Response.Write(String.Format(
"{0}#Type={1}#Visible={2}#CanGetText={3}#Text={4}\n"
InBlock.gif                        field.HeaderText, field.GetType().Name.ToString(), field.Visible, 
!String.IsNullOrEmpty(text), text));
ExpandedSubBlockEnd.gif                }

InBlock.gif                Response.Write(
"</pre>");
InBlock.gif                
break;
ExpandedSubBlockEnd.gif        }

ExpandedSubBlockEnd.gif    }

InBlock.gif    
InBlock.gif    
void LoadProductData()
ExpandedSubBlockStart.gifContractedSubBlock.gif    
dot.gif{
InBlock.gif        DataTable dt 
= CreateProductTable();
InBlock.gif
InBlock.gif        GridView1.DataSource 
= dt;
InBlock.gif        GridView1.DataBind();
ExpandedSubBlockEnd.gif    }

InBlock.gif
InBlock.gif    #region sample data
InBlock.gif
InBlock.gif    static DataTable CreateProductTable()
ExpandedSubBlockStart.gifContractedSubBlock.gif    
dot.gif{
InBlock.gif        DataTable tbl 
= new DataTable("Products");
InBlock.gif
InBlock.gif        tbl.Columns.Add(
"ProductID"typeof(int));
InBlock.gif        tbl.Columns.Add(
"ProductName"typeof(string));
InBlock.gif        tbl.Columns.Add(
"CategoryID"typeof(int));
InBlock.gif        DataRow row 
= tbl.NewRow();
InBlock.gif        row[
0= 1;
InBlock.gif        row[
1= "Chai";
InBlock.gif        row[
2= 1;
InBlock.gif        tbl.Rows.Add(row);
InBlock.gif
InBlock.gif        row 
= tbl.NewRow();
InBlock.gif        row[
0= 2;
InBlock.gif        row[
1= "Chang";
InBlock.gif        row[
2= 1;
InBlock.gif        tbl.Rows.Add(row);
InBlock.gif
InBlock.gif        row 
= tbl.NewRow();
InBlock.gif        row[
0= 3;
InBlock.gif        row[
1= "Aniseed Syrup";
InBlock.gif        row[
2= 2;
InBlock.gif        tbl.Rows.Add(row);
InBlock.gif
InBlock.gif        row 
= tbl.NewRow();
InBlock.gif        row[
0= 4;
InBlock.gif        row[
1= "Chef Anton's Cajun Seasoning";
InBlock.gif        row[
2= 2;
InBlock.gif        tbl.Rows.Add(row);
InBlock.gif
InBlock.gif        row 
= tbl.NewRow();
InBlock.gif        row[
0= 5;
InBlock.gif        row[
1= "Chef Anton's Gumbo Mix";
InBlock.gif        row[
2= 2;
InBlock.gif        tbl.Rows.Add(row);
InBlock.gif
InBlock.gif        row 
= tbl.NewRow();
InBlock.gif        row[
0= 47;
InBlock.gif        row[
1= "Zaanse koeken";
InBlock.gif        row[
2= 3;
InBlock.gif        tbl.Rows.Add(row);
InBlock.gif
InBlock.gif        row 
= tbl.NewRow();
InBlock.gif        row[
0= 48;
InBlock.gif        row[
1= "Chocolade";
InBlock.gif        row[
2= 3;
InBlock.gif        tbl.Rows.Add(row);
InBlock.gif
InBlock.gif        row 
= tbl.NewRow();
InBlock.gif        row[
0= 49;
InBlock.gif        row[
1= "Maxilaku";
InBlock.gif        row[
2= 3;
InBlock.gif        tbl.Rows.Add(row);
InBlock.gif
InBlock.gif        
return tbl;
ExpandedSubBlockEnd.gif    }

InBlock.gif
InBlock.gif    #endregion  
InBlock.gif    
InBlock.gif    protected 
void Button1_Click(object sender, EventArgs e)
ExpandedSubBlockStart.gifContractedSubBlock.gif    
dot.gif{
InBlock.gif        LoadProductData();
ExpandedBlockEnd.gif    }

None.gif
</script>
None.gif
None.gif
<html xmlns="http://www.w3.org/1999/xhtml" >
None.gif
<head runat="server">
None.gif    
<title>Demo6_AccessHiddenGridViewColumnValue</title>
None.gif
</head>
None.gif
<body>
None.gif    
<form id="form1" runat="server">
None.gif    
<div>
None.gif        
<asp:GridView ID="GridView1" DataKeyNames="ProductId,CategoryId" runat="server" AutoGenerateColumns="False" OnRowCommand="GridView1_RowCommand" OnRowDataBound="GridView1_RowDataBound"  CellPadding="4" ForeColor="#333333">
None.gif            
<Columns>
None.gif                
<asp:BoundField DataField="ProductID" HeaderText="列0 正常状态"/>
None.gif                
<asp:BoundField DataField="ProductID" HeaderText="列1 直接设置Visible=false 无法获取值" Visible="False" />
None.gif                
<asp:BoundField DataField="ProductID" HeaderText="列2 width=0 客户端依然呈现无效">
None.gif                    
<ItemStyle Width="0px" />
None.gif                
</asp:BoundField>        
None.gif                
<asp:BoundField DataField="ProductID" HeaderText="列3 客户端 CSS 控制隐藏,不安全,毕竟数据还是呈现到客户端了"/>
None.gif                
<asp:BoundField DataField="ProductID" HeaderText="列4 设置单元格隐藏, TableCell.Visible=false, OK"/>                
None.gif                
<asp:TemplateField HeaderText="列5 模板列直接调用 Eval " Visible="False">
None.gif                    
<ItemTemplate>
ExpandedBlockStart.gifContractedBlock.gif                        
<%dot.gifEval("ProductID"%>
None.gif                    
</ItemTemplate>
None.gif                
</asp:TemplateField>                
None.gif                
<asp:TemplateField HeaderText="列6 模板列嵌入 Label" Visible="False">
None.gif                    
<ItemTemplate>
None.gif                        
<asp:label ID="lblProductID" runat="server" Text='<%# Eval("ProductID") %>' />
None.gif                    
</ItemTemplate>
None.gif                
</asp:TemplateField> 
None.gif                
<asp:BoundField DataField="ProductName" HeaderText="列7"/>  
None.gif                
<asp:ButtonField CommandName="Select" Text="Select" HeaderText="列8 按钮" />
None.gif            
</Columns>
None.gif            
<FooterStyle BackColor="#990000" Font-Bold="True" ForeColor="White" />
None.gif            
<RowStyle BackColor="#FFFBD6" ForeColor="#333333" />
None.gif            
<SelectedRowStyle BackColor="#FFCC66" Font-Bold="True" ForeColor="Navy" />
None.gif            
<PagerStyle BackColor="#FFCC66" ForeColor="#333333" HorizontalAlign="Center" />
None.gif            
<HeaderStyle BackColor="#990000" Font-Bold="True" ForeColor="White" />
None.gif            
<AlternatingRowStyle BackColor="White" />
None.gif        
</asp:GridView></div>
None.gif        
<asp:Button ID="Button1" runat="server" OnClick="Button1_Click" Text="重新绑定数据" />
None.gif    
</form>
None.gif
</body>
None.gif
</html>
None.gif

示例下载
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值