我有一个详细信息视图,我希望其中一个字段具有从不同标签获取的默认值,而该标签又取自上一页。
视图的代码是:
<asp:DetailsView ID="DetailsView1" runat="server" AutoGenerateRows="False" DataKeyNames="gkey" DataSourceID="SqlDataSourceEmployees" Height="50px" Width="125px" OnLoad="DetailsView1_Load">
<Fields>
<asp:BoundField DataField="gkey" HeaderText="gkey" InsertVisible="False" ReadOnly="True" SortExpression="gkey" />
<asp:TemplateField HeaderText="Department" SortExpression="Department">
<EditItemTemplate>
<asp:TextBox ID="TextBox1" runat="server" Text='<%# Bind("Department") %>'></asp:TextBox>
</EditItemTemplate>
<InsertItemTemplate>
<asp:TextBox ID="TextBox1" runat="server" Text='<%# Bind("Department") %>'></asp:TextBox>
</InsertItemTemplate>
<ItemTemplate>
<asp:Label ID="Label1" runat="server" Text='<%# Bind("Department") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:BoundField DataField="name" HeaderText="name" SortExpression="name" />
<asp:BoundField DataField="SIP" HeaderText="SIP" SortExpression="SIP" />
<asp:BoundField DataField="color" HeaderText="color" SortExpression="color" />
<asp:CheckBoxField DataField="on_call" HeaderText="on_call" SortExpression="on_call" />
<asp:CheckBoxField DataField="on_leave" HeaderText="on_leave" SortExpression="on_leave" />
<asp:CommandField ShowDeleteButton="True" ShowEditButton="True" ShowInsertButton="True" />
</Fields>
</asp:DetailsView>
现在我正在尝试设置TextBox1的值
protected void Page_Load(object sender, EventArgs e)
{
((TextBox)DetailsView1.FindControl("TextBox1")).Text = LabelSelectedDepartament.Text;
}
但是这给了我一个NullReferenceException。我试图将相同的行放到DetailsVie1_load,但这会产生相同的错误。我错过了什么?
编辑:我正在从上一页正确传输数据,我刚刚跳过那部分,因为它不相关,但是因为你坚持:
protected void Page_Load(object sender, EventArgs e)
{
Page previousPage = Page.PreviousPage;
if (previousPage != null)
{
Label tst = FindControlRecursive(previousPage, "lblDepartment") as Label;
LabelSelectedDepartament.Text = tst.Text;
//And here is error
((TextBox)DetailsView1.FindControl("TextBox1")).Text = LabelSelectedDepartament.Text;
}
}
//This fantastic procedure below allows to find controls within controls (i.e. label inside the table)
private Control FindControlRecursive(Control root, string id)
{
if (root.ID == id)
{
return root;
}
foreach (Control c in root.Controls)
{
Control t = FindControlRecursive(c, id);
if (t != null)
{
return t;
}
}
return null;
}
Edit2:我不是在寻找PreviousPage中的值,它已经在当前页面上(并且它正确显示),所以我需要的是像
TextBox1.Text=LabelSelectedDepartament.Text
EDIT3
我试图将((TextBox)DetailsView1.FindControl("TextBox1")).Text = LabelSelectedDepartament.Text;
放入
我想我的解决方法有些不对。
答案 0 :(得分:0)
您可以访问DetailsView的DataBound事件中的TextBox1。在数据绑定之前,在该控件中没有任何东西可以找到。