我将值从gridview传递到下一页。 gridview连接到数据库.gridview显示我想要的数据但当我尝试将gridview的行数据传递到下一页时,它会抛出一个错误'对象引用未设置为对象的实例&#39 ;
gridview如下:
<asp:GridView ID="GridView1" HeaderStyle-BackColor="#3AC0F2" HeaderStyle-ForeColor="White"
RowStyle-BackColor="#A1DCF2" AlternatingRowStyle-BackColor="White" AlternatingRowStyle-ForeColor="#000"
runat="server" AutoGenerateColumns="False" DataSourceID="SqlDataSource1" AllowPaging="True">
<AlternatingRowStyle BackColor="White" ForeColor="#000000"></AlternatingRowStyle>
<Columns>
<asp:BoundField DataField="TaskId" HeaderText="TaskId" ItemStyle-Width="30" InsertVisible="False" ReadOnly="True" SortExpression="TaskId" />
<asp:BoundField DataField="Title" HeaderText="Title" ItemStyle-Width="150" SortExpression="Title" />
<asp:BoundField DataField="Body" HeaderText="Body" SortExpression="Body" />
<asp:BoundField DataField="Reward" HeaderText="Reward" SortExpression="Reward" />
<asp:BoundField DataField="TimeAllotted" HeaderText="TimeAllotted" SortExpression="TimeAllotted" />
<asp:BoundField DataField="PosterName" HeaderText="PosterName" SortExpression="PosterName" />
<asp:TemplateField>
<ItemTemplate>
<asp:LinkButton ID="lnkDetails" runat="server" Text="Send Details" PostBackUrl='<%# "~/test/Tasks.aspx?RowIndex=" + Container.DataItemIndex %>'></asp:LinkButton>
</ItemTemplate>
</asp:TemplateField>
</Columns>
<HeaderStyle BackColor="#3AC0F2" ForeColor="White"></HeaderStyle>
<RowStyle BackColor="#A1DCF2"></RowStyle>
</asp:GridView>
<asp:SqlDataSource ID="SqlDataSource1" runat="server" ConnectionString="<%$ ConnectionStrings:ABCD %>" SelectCommand="SELECT * FROM [Task]"></asp:SqlDataSource>
&task; .aspx.cs&#39;的代码如下:
protected void Page_Load(object sender, EventArgs e)
{
if (this.Page.PreviousPage != null)
{
int rowIndex = int.Parse(Request.QueryString["RowIndex"]);
GridView GridView1 = (GridView)this.Page.PreviousPage.FindControl("GridView1");
GridViewRow row = GridView1.Rows[rowIndex];
lblTaskId.Text = row.Cells[0].Text;
lblTitle.Text = row.Cells[1].Text;
lblBody.Text = row.Cells[2].Text;
lblReward.Text = row.Cells[3].Text;
lblTimeAllotted.Text = row.Cells[4].Text;
lblPosterName.Text = row.Cells[5].Text;
}
}
我在下面的一行收到错误消息:
GridViewRow row = GridView1.Rows[rowIndex];
答案 0 :(得分:3)
似乎FindControl
方法实际上找不到控件,使您的GridView1
变量为null。确保控件在页面内部并且名称正确。
修改强>
如果您使用母版页,那么FindControl
确实存在一些问题。 Rick Strahls在his blog中解释了它:
*The problem is that when you use MasterPages the page hierarchy drastically changes.
Where a simple this.FindControl() used to give you a control instance you now have to
drill into the container hierarchy pretty deeply just to get to the content container.*
他还有一个如何让它发挥作用的例子。基本上,您必须从母版页中找到您的内容控件(使用page.Master.FindControl
)。然后从 点开始,您应该能够访问网格控件。
在您的方案中,因为您需要上一页的控件:
var GridView1 = page.PreviousPage.Master.FindControl("ContentContainer").FindControl("GridView1") as GridView;
答案 1 :(得分:0)
在我看来,当&#34; this.Page.PreviousPage!= null&#34;时,你的gridview没有任何绑定数据。是真的。也就是说,除非您在其他初始化处理程序中绑定数据。
因为没有数据,所以没有Rows意味着GridView1.Rows [rowIndex]将为null。