我正在使用ASP.NET 4和MVC并尝试添加代码来处理“选择”链接。一旦用户选择了行,我需要显示一个包含更多细节的新页面。我试图捕获rowcommand但我从来没有打过断点。这是我当前第一页的GridView代码 -
<%@ Page Title="" Language="C#" MasterPageFile="~/Views/Shared/Site.Master" Inherits="System.Web.Mvc.ViewPage<IEnumerable<ValidationPortal.Models.Contact>>" %>
<asp:Content ID="Content2" ContentPlaceHolderID="MainContent" runat="server">
<form id="form1" runat="server">
<h2>Index</h2>
<p>
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False"
DataKeyNames="Id" DataSourceID="SqlDataSource1">
<Columns>
<asp:CommandField ShowSelectButton="True" />
<asp:BoundField DataField="Id" HeaderText="Id" InsertVisible="False"
ReadOnly="True" SortExpression="Id" />
<asp:BoundField DataField="FirstName" HeaderText="FirstName"
SortExpression="FirstName" />
<asp:BoundField DataField="LastName" HeaderText="LastName"
SortExpression="LastName" />
<asp:BoundField DataField="Phone" HeaderText="Phone" SortExpression="Phone" />
<asp:BoundField DataField="Email" HeaderText="Email" SortExpression="Email" />
</Columns>
</asp:GridView>
<asp:SqlDataSource ID="SqlDataSource1" runat="server"
ConnectionString="<%$ ConnectionStrings:ConnectionString %>"
SelectCommand="SELECT * FROM [Contacts]"></asp:SqlDataSource>
</p>
</form>
</asp:Content>
我需要添加什么才能使其正常工作?
答案 0 :(得分:2)
我认为您需要在网格标记中指定OnSelectedIndexChanged事件。您的活动可能只是重定向到您的详细信息页面,其中包含所选项目的ID。它看起来像这样:
网格:
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False"
DataKeyNames="Id" DataSourceID="SqlDataSource1"
OnSelectedIndexChanged="SelectEvent">
// rest of grid definitions
</asp:GridView>
C#:
protected void SelectEvent(object sender, EventArgs e)
{
if (GridView1.SelectedIndex >= 0)
Response.Redirect("yourpage.aspx?itemid=" + (int)GridView1.SelectedValue);
}
就个人而言,我会跳过select命令并创建一个带有指向您网址链接的项目模板,如图所示here
答案 1 :(得分:0)
试试这种方式
protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
{
if (e.CommandName == "Select")
{
// Do something
}
}
如果您不想使用row命令或者想要显式触发rowcommand,请使用以下代码段
int GridView1TotalCount = GridView1.Rows.Count;
int r = Convert.ToInt32(dslno)-1;
if (r != -1)
{
if (GridView1TotalCount > r)
{
GridViewRow thisGridView1 = GridView1.Rows[r];
ClientScript.GetPostBackClientHyperlink(this.GridView1, "Select$" + thisGvEmpMaster.RowIndex);
// Do something here you have datakey like
int dkkey = Convert.ToString(GridView1.DataKeys[thisGridView1.RowIndex].Value);
}
}