2

我有一个 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' 始终为空。我确信这是一个简单的解决方法,但在谷歌搜索问题后,我还没有找到任何可行的方法。

这是我在 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" />
4

1 回答 1

0

试试这个以获得选定的行

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

}
于 2013-08-23T18:43:18.927 回答