GridView中DataKeyNames的应用小结
11:02:35]

很多时候我们需要在GridView的RowCommand之类的事件中需要获取当前行的一些关联性的数据值。但这些数据值又没有直接体现在GridView的列中。这个时候该怎么办呢?
有同学喜欢用隐藏列的方式,把需要使用但不显示的字段绑定到此列上,同时设置列宽为0或不显示,使用时可以用常规的取某行某列的方式来获取数据。
但是在Framework 2.0中,我们可以采用DataKeyNames的方式来获取此类数据。

代码示例:
(前台)

(转)GridView中使用DataKeyNames存储数据键值        <asp:GridView ID="GridView1" runat="server" DataKeyNames="Grup" OnRowCommand="GridView1_RowCommand" AutoGenerateColumns="False">
(转)GridView中使用DataKeyNames存储数据键值           
<Columns>
(转)GridView中使用DataKeyNames存储数据键值               
<asp:TemplateField>
(转)GridView中使用DataKeyNames存储数据键值                   
<ItemTemplate>
(转)GridView中使用DataKeyNames存储数据键值                       
<asp:Label ID="Label1" runat="server" Text='<%#Eval("GrupName") %>'></asp:Label>
(转)GridView中使用DataKeyNames存储数据键值                   
</ItemTemplate>
(转)GridView中使用DataKeyNames存储数据键值               
</asp:TemplateField>
(转)GridView中使用DataKeyNames存储数据键值               
<asp:ButtonField Text="按钮" />
(转)GridView中使用DataKeyNames存储数据键值           
</Columns>
(转)GridView中使用DataKeyNames存储数据键值       
</asp:GridView>
Grup 为我们想使用但不需要显示的列。(如果有多个字段,使用逗号分开)
(后台)
(转)GridView中使用DataKeyNames存储数据键值    protected void Page_Load(object sender, EventArgs e)
    }


顺便补充一句。
如果你使用模板列中放置按钮控件的方式,要想在按钮事件中获取这种字段值就更简单了。

只需要在按钮的CommandArgument属性设置为想绑定的字段,如:

(转)GridView中使用DataKeyNames存储数据键值<asp:TemplateField>
(转)GridView中使用DataKeyNames存储数据键值    
<ItemTemplate>
(转)GridView中使用DataKeyNames存储数据键值        
<asp:Button ID="Button2" runat="server" OnClick="Button2_Click" Text="Button" CommandArgument=' <%#Eval("Grup") %>' />
(转)GridView中使用DataKeyNames存储数据键值    
</ItemTemplate>
(转)GridView中使用DataKeyNames存储数据键值
</asp:TemplateField>


按钮事件中如是写:

(转)GridView中使用DataKeyNames存储数据键值protected void Button2_Click(object sender, EventArgs e)

 

 

 

相关文章:

  • 2022-01-06
  • 2021-06-23
  • 2021-10-24
  • 2022-12-23
  • 2022-02-10
  • 2022-12-23
  • 2021-06-10
  • 2022-12-23
猜你喜欢
  • 2021-07-02
  • 2021-12-02
  • 2021-12-10
  • 2022-12-23
  • 2022-12-23
相关资源
相似解决方案