DataGrid中的添加链接的两种方法比较

引言:Asp.net 的应用中,很多时候需要在DataGrid 中添加链接。通常添加链接的方法就是通过模板列TemplateColumn 。在模板列中放入一个LinkButton,来实现链接转向。

说明:绑定DataGrid的数据源的Sql语句例如:“SELECT Clhm,lsh FROM  TABLE1”

基于以上说明,我将说明以下两中方法:
方法一:在DataGrid中添加ItemCommand事件
JavaScript 代码如下
     <asp:TemplateColumn SortExpression="Clhm" HeaderText="车牌号码">
            <HeaderStyle HorizontalAlign="Center"></HeaderStyle>
            <ItemStyle HorizontalAlign="left" width="20%"></ItemStyle>
            <ItemTemplate>
             <asp:LinkButton id="lnkClhm" runat="server" CommandName="look" text='<%# DataBinder.Eval(Container,"DataItem.Clhm") %>'>
                         </asp:LinkButton>
            <asp:Label id="Lsh" visiable="false" runat="server" text='<%# DataBinder.Eval(Container,"DataItem.Lsh") %>'></asp:Label>
            </ItemTemplate>
           </asp:TemplateColumn>

在ItemCommand事件中添加如下代码
private void dvList_ItemCommand(object source, System.Web.UI.WebControls.DataGridCommandEventArgs e)
  {   
       if(e.CommandName=="look")
       {  

        Label Lsh= (Label)e.Item.FindControl("Lsh");
        string str= TaskId.Text;    
        Response.Write("<script>__doUpdate('" + str+ "');"<script>");   
    }
  }

方法二:在DataGrid中添加ItemDataBound事件
JavaScript 代码如下
<asp:TemplateColumn SortExpression="Clhm" HeaderText="车牌号码">
            <HeaderStyle HorizontalAlign="Center"></HeaderStyle>
            <ItemStyle HorizontalAlign="left" width="20%"></ItemStyle>
            <ItemTemplate>
             <asp:LinkButton id="lnkClhm" runat="server" CommandName="look" text='<%# DataBinder.Eval(Container,"DataItem.Clhm") %>'>
             </asp:LinkButton>
            </ItemTemplate>
           </asp:TemplateColumn>
在ItemDataBound事件中添加如下代码
if(e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem)
   {
        string Lsh= ((DataRowView)e.Item.DataItem).Row["lsh"].ToString();
        ((LinkButton)e.Item.FindControl("lnkClhm")).Attributes["onclick"] = "return __doUpdate('" + Lsh+ "');";        
   }

 

posted @ 2007-08-31 13:19  笑萧亦然  阅读(365)  评论(0)    收藏  举报