我有一个GridView,它使用实体框架从LINQ查询中获取数据。现在,我希望能够单击一行来填充位于gridview旁边的updatepanel,其中包含所单击行上对象的属性。
现在这就是我到目前为止:
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" AllowPaging="True" AllowSorting="True" OnRowDataBound="GridView1_RowDataBound">
<Columns>
<asp:BoundField DataField="Title" HeaderText="Title" SortExpression="Title" />
<asp:BoundField DataField="Payment" HeaderText="Payment" SortExpression="Payment" />
<asp:BoundField DataField="Creator" HeaderText="Creator" SortExpression="Creator" />
<asp:BoundField DataField="JobId" HeaderText="JobId" SortExpression="JobId" />
</Columns>
[...]
</asp:GridView>
</div>
<div class="center">
<asp:ScriptManager ID="ScriptManager1" runat="server" EnablePartialRendering="True">
</asp:ScriptManager>
<asp:UpdatePanel ID="UpdatePanel1" runat="server" UpdateMode="Conditional">
<ContentTemplate>
<div class="wrapper">
<div class="ProfileTop">
<asp:Label ID="JobTitle" runat="server" Text=""></asp:Label>
</div>
<div class="left">
<asp:Label ID="JobDescription" runat="server" Text=""></asp:Label>
</div>
<div class="right">
<asp:Label ID="JobCreator" runat="server" Text=""></asp:Label>
</div>
</div>
</ContentTemplate>
<Triggers>
<asp:AsyncPostBackTrigger ControlID="GridView1" EventName="SelectedIndexChanged" />
</Triggers>
</asp:UpdatePanel>
现在背后的代码如下:
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
int theJobId = (int)DataBinder.Eval(e.Row.DataItem, "JobId");
Session["JobToShow"] = theJobId;
e.Row.Attributes.Add("onclick",
Page.ClientScript.GetPostBackEventReference(GridView1, "Select$" + e.Row.RowIndex.ToString()));
e.Row.Style["cursor"] = "pointer";
}
}
protected void GridView1_SelectedIndexChanged(object sender, EventArgs e)
{
int c = (int)Session["JobToShow"];
var currentJob = JobDataFactory.RetrieveJob(c);
JobTitle.Text = currentJob.Title;
JobDescription.Text = currentJob.Descripton;
}
我尝试了几种不同的方法,但没有运气。我可以单击gridview行,并触发updatepanel以使用新数据进行更新。但遗憾的是,它不是点击行的属性,而是来自最新创建的行。所以我的问题是如何捕获已被点击的行,因此我可以使用它来更新更新面板中的正确信息。
修改
protected void GridView1_SelectedIndexChanged(object sender, EventArgs e)
{
var row = GridView1.SelectedRow;
int c = Convert.ToInt32(row.Cells[3].Text);
var currentJob = JobDataFactory.RetrieveJob(c);
来自speti43的代码完成了这个技巧,只需转换而不是强制转换。
答案 0 :(得分:0)
不需要在Session中存储它。
您可以将GridViewSelectEventArgs用于SelectedIndexChanging事件:
protected void GridView1_SelectedIndexChanging(object sender, GridViewSelectEventArgs e)
{
var row = GridView1.Rows[e.NewSelectedIndex];
int c = (int)row.Cells[x].Text ; //x is the number of appropriate column
var currentJob = JobDataFactory.RetrieveJob(c);
或
protected void GridView1_SelectedIndexChanged(object sender, EventArgs e)
{
var row = CustomersGridView.SelectedRow;
int c = (int)row.Cells[x].Text ; //x is the number of appropriate column
var currentJob = JobDataFactory.RetrieveJob(c);