当用户单击gridview行时,如何调用函数后面的代码?

时间:2011-05-07 11:49:46

标签: asp.net gridview code-behind

我在一个带有c#代码的aspx页面中有一个gridview。

当用户点击某一行的任何地方时,有没有办法在函数后面运行代码?现在,我使用选择按钮。但随后用户必须单击该按钮。我希望用户能够点击一行中的任意位置,在另一个位于主网格视图旁边的网格视图中显示其详细信息。

这里有一些关于如何做到这一点的想法?

谢谢!

1 个答案:

答案 0 :(得分:2)

试试这个

<asp:GridView runat="server" ID="GridView1" DataKeyNames="ID" AutoGenerateColumns="False"
        Font-Names="Tahoma" Font-Size="Small" OnSelectedIndexChanged="GridView1_SelectedIndexChanged"
        OnRowDataBound="GridView1_RowDataBound">
        <Columns>
            <asp:TemplateField HeaderText="Row">
                <ItemTemplate>
                    <%# Container.DataItemIndex+1 %>
                </ItemTemplate>
            </asp:TemplateField>
            <asp:BoundField DataField="FirstName" HeaderText="First Name" />
            <asp:BoundField DataField="LastName" HeaderText="Last Name" />
            <asp:CommandField ShowSelectButton="true" ButtonType="Link" Visible="false" SelectText="Enroll" />
        </Columns>
    </asp:GridView>


 protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            GridView1.DataSource = Enumerable.Range(1, 10).Select(a => new
            {
                ID = a,
                FirstName = String.Format("First {0}", a),
                LastName = String.Format("Last{0}", a)
            });
            GridView1.DataBind();
        }
    }
    protected void GridView1_SelectedIndexChanged(object sender, EventArgs e)
    {

        //Bind other grid

        Response.Write(GridView1.SelectedIndex+1);

    }
    protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
    {
        if (e.Row.RowType == DataControlRowType.DataRow)
        {
            //add css to GridViewrow based on rowState
            e.Row.CssClass = e.Row.RowState.ToString();
            //Add onclick attribute to select row.
            e.Row.Attributes.Add("onclick", String.Format("javascript:__doPostBack('GridView1','Select${0}')", e.Row.RowIndex));
        }
    }