1、gridview中用的是按扭控件imagebutton,

  

    .aspx

 

     <asp:GridView ID="GridView_user" runat="server" AutoGenerateColumns="False" OnRowDataBound="GridView_user_RowDataBound"
                        Width="99%" OnRowCommand="GridView_user_RowCommand">
                        <Columns>
                            <asp:TemplateField HeaderText="选择">
                                <ItemTemplate>
                                    <asp:ImageButton ID="ImageButton_select" runat="server" ImageUrl="~/images/Select.gif" CommandName ="ib_sel" CommandArgument ='<%# Eval("user_sn")%>' />
                                </ItemTemplate>
                                <ItemStyle Width="30px" />
                            </asp:TemplateField>
                            <asp:BoundField DataField="user_sn" HeaderText="用户名称" />
                            <asp:BoundField DataField="user_Givename" HeaderText="工号" />
                                                   </Columns>
                    </asp:GridView>

 

 

2、后台写了一个数据源的绑定,完成的操作是当选中某行时,获得应行上的“用户名称”和“工号”的两个字段的值,大家已经看到,在.aspx页上已经在ImageButton 按扭上绑定了“用户名称”的值,即CommandArgument ='<%# Eval("user_sn")%>'  ;那么我们只要再获得“工号”的值就可以了,

接下来,我们来看一下在后台.aspx.cs文件中如何写:

 

.aspx.cs

 

/*初始化gridview绑定*/

 

  void DBind(DataTable dt)
    {
        string[] str = new string[] { "user_Givename" };        

        this.GridView_user.DataKeyNames = str;                //这里是设置主键

        GridView_user.DataSource = dt;             //  注:dt 这里是一个已经事先写好的datatable列表的数据源,这里你可以换成你自己要用的数据源的绑定。
        GridView_user.DataBind();
     }

 

 

/*功能:当选中某行时,获得应行上的“用户名称”和“工号”的两个字段的值*/

/*关键就是这里的实现喽*/

 

    protected void GridView_user_RowCommand(object sender, GridViewCommandEventArgs e)
    {
        if (e.CommandName == "ib_sel")
        {
            string name = e.CommandArgument.ToString();

            Control cmdSource = e.CommandSource as Control;
            GridView gridv = sender as GridView;
            GridViewRow row = cmdSource.NamingContainer as GridViewRow;
            int rowIndex = row.RowIndex;
            string workno = gridv.DataKeys[rowIndex].Value.ToString();          //获得选中行的“工号”字段的值
           

            string strword = name+ "(" + workno + ")";   

            

           ClientScript.RegisterStartupScript(Page.GetType(), "script", "alert('"+strword.Trim()+"')", true);        
        }
    }

 

3、现在就完成了,运行一下看看效果吧,仅供参考,如果有更好的方法,欢迎大家跟贴,在此向大家学习了。^0^

posted on 2008-08-21 14:23  forever of Provence  阅读(2786)  评论(0编辑  收藏  举报