GridView中控件列使用方法小结

方法一.使用GridView自带ButtonField控件。典型代码如下:

<%@ Page language="C#" %>

<script runat="server">

  
void CustomersGridView_RowCommand(Object sender, GridViewCommandEventArgs e)
  {
  
    
// If multiple ButtonField column fields are used, use the
    
// CommandName property to determine which button was clicked.
    if(e.CommandName=="Select")
    {
    
      
// Convert the row index stored in the CommandArgument
      
// property to an Integer.
      int index = Convert.ToInt32(e.CommandArgument);    
    
      
// Get the last name of the selected author from the appropriate
      
// cell in the GridView control.
      GridViewRow selectedRow = CustomersGridView.Rows[index];
      TableCell contactName 
= selectedRow.Cells[1];
      
string contact = contactName.Text;  
    
      
// Display the selected author.
      Message.Text = "You selected " + contact + ".";
      
    }
    
  }
    
</script>

<html>
  
<body>
    
<form runat="server">
        
      
<h3>ButtonField Example</h3>
      
      
<asp:label id="Message"
        forecolor
="Red"
        runat
="server"/>
                    
      
<!-- Populate the Columns collection declaratively. -->
      
<asp:gridview id="CustomersGridView" 
        datasourceid
="CustomersSqlDataSource" 
        autogeneratecolumns
="false"
        onrowcommand
="CustomersGridView_RowCommand"
        runat
="server">
                
        
<columns>
                
          
<asp:buttonfield buttontype="Button" 
            commandname
="Select"
            headertext
="Select Customer" 
            text
="Select"/>
          
<asp:boundfield datafield="CompanyName" 
            headertext
="Company Name"/>
          
<asp:boundfield datafield="ContactName" 
            headertext
="Contact Name"/>
                
        
</columns>
                
      
</asp:gridview>
            
        
<!-- This example uses Microsoft SQL Server and connects -->
        
<!-- to the Northwind sample database.                   -->
        
<asp:sqldatasource id="CustomersSqlDataSource"  
          selectcommand
="Select [CustomerID], [CompanyName], [ContactName], [ContactTitle] From [Customers]"
          connectionstring
="<%$ ConnectionStrings:NorthWindConnection%>"
          runat
="server">
        
</asp:sqldatasource>
            
    
</form>
  
</body>
</html>

 

以上代码来源于Msdnhttp://msdn.microsoft.com/zh-cn/library/system.web.ui.webcontrols.buttonfield(VS.80).aspx,原来自己以为ButtonField没有办法取到行号,可是在以上这个示例中显示,ButtonField已经自带了这个属性,只要在RowCommand事件中,转换一下e.CommandArgument即可。

方法二.运用模版列。该方法比较灵活。可以自指定CommandArgument绑定数据源上某一字段。典型代码如下:

CommandArgument='<%# Eval("Id") %>'

另:无论是方法一还是方法二,只要有办法取出GridView中事件源所在行号,那么也可以结合设置GridViewDataKeyNames属性,来获取数据源相关关键字,进行事件操作。

posted @ 2009-07-15 09:06  Shapley  阅读(377)  评论(0编辑  收藏  举报