获取所选行按钮单击

时间:2013-08-23 18:16:48

标签: c# asp.net gridview

我有一个GridView,可以执行以下操作:

protected override void Render(System.Web.UI.HtmlTextWriter textWriter)
    {
        foreach (GridViewRow gvRow in gvNotifications.Rows)
        {
            if (gvRow.RowType == DataControlRowType.DataRow)
            {
                gvRow.Attributes.Add("onmouseover", "this.previous_color=this.style.backgroundColor;this.style.backgroundColor='#FFFF99';this.style.cursor='hand';");
                gvRow.Attributes.Add("onmouseout", "this.style.backgroundColor=this.previous_color;");
                gvRow.Attributes["onclick"] = ClientScript.GetPostBackClientHyperlink(gvNotifications, "Select$" + gvRow.RowIndex,true);
            }
        }

        base.Render(textWriter);
    }

    protected void gvNotifications_SelectedIndexChanged(object sender, EventArgs e)
    {
        gvNotifications.SelectedRowStyle.BackColor = Color.LightBlue;
    }

我有一个名为btnTest的按钮,我希望能够将当前行转换为我的自定义对象。我没有运气就试过以下。

Customer currentRow = (Customer)gvNotifications.SelectedRow.DataItem;

'DataItem'始终为null。我确信这是一个简单的解决办法,但谷歌搜索问题后我还没有找到任何可行的方法。

这是我在aspx中的GridView:

<asp:GridView 
    ID="gvNotifications"
    runat="server"
    AutoGenerateColumns="false"
    GridLines="None"
    CssClass="mGrid"
    AlternatingRowStyle-BackColor="#F0F0F0"
    AllowPaging="true"
    AllowSorting="true"
    PagerStyle-CssClass="pgr"
    PageSize="25"
    OnPageIndexChanging="gvNotifications_PageIndexChanging"
    OnSorting="gvNotifications_Sorted" HeaderStyle-CssClass="srtAc" 
    onselectedindexchanged="gvNotifications_SelectedIndexChanged">
    <Columns>
        <asp:TemplateField HeaderText="Customer Id" SortExpression="CustomerId" HeaderStyle-ForeColor="WhiteSmoke">
            <ItemTemplate>
                <%#Eval("CustomerId")%>
            </ItemTemplate>
        </asp:TemplateField>
        <asp:TemplateField HeaderText="Contact Name" SortExpression="ContactName" HeaderStyle-ForeColor="WhiteSmoke">
            <ItemTemplate>
                <%#Eval("ContactName")%>
            </ItemTemplate>
        </asp:TemplateField>
    </Columns>
</asp:GridView>
<asp:Button ID="btnTest" runat="server" Text="Use" onclick="btnTest_Click" />

1 个答案:

答案 0 :(得分:0)

尝试此选择行

protected void YourGridView_SelectedIndexChanged(object sender, EventArgs e)
{
     //Grab the selected row
     GridViewRow row = YourGridViewId.SelectedRow;

}
相关问题