DataList + FindControl()

C

christof

How to do it:

My page:

<asp:DataList ID="dataListRoleMembers" ...>
....
<FooterTemplate>
<asp:LinkButton ID="btnAddMember" runat="server"
OnClick="btnAddMember_Click">Add...</asp:LinkButton>
<asp:TextBox ID="txtAddMember" runat="server"></asp:TextBox>
</FooterTemplate>
</asp:DataList>

Code behind:

protected void btnAddMember_Click(object sender, EventArgs e)
{
TextBox txtMember =
(TextBox)dataListRoleMembers.FindControl("txtAddMember");
....

}
txtMember is null, FindControl don't get it for me - why?

I've tried also:
Control ctrl = dataListRoleMembers.FindControl("txtAddMember");
but result was the same, null

Thanks for help!
 
N

Nathan Sokalski

I believe the problem is because of how you are calling the FindControl
method. FindControl needs to know which Item it is looking in because a
DataList contains many copies of each Control that is in a template, so you
need to call it as a method of an Item. Here is an example of where I used
in some code of mine to set the Text property of a Label (my code is in
VB.NET, but it should be similar in C#)


Private Sub datResults_ItemDataBound(ByVal sender As Object, ByVal e As
System.Web.UI.WebControls.DataListItemEventArgs) Handles
datResults.ItemDataBound

CType(e.Item.FindControl("lblPhone1"), Label).Text = "&nbsp;"

End Sub


Notice that I used e.Item.FindControl when calling the FindControl method. I
don't know what event is calling your method, so if you need help figuring
out how to determine which Item called it, let me know. But something that
it looks like you need to read up on a little bit is Event Bubbling (this is
where you use the CommandName and CommandArgument properties of the
Button/LinkButton/ImageButton Controls). Good Luck!
 
C

christof

Nathan said:
I believe the problem is because of how you are calling the FindControl
method. FindControl needs to know which Item it is looking in because a
DataList contains many copies of each Control that is in a template, so you
need to call it as a method of an Item.
[...]
At the beginning i thought that in footer it is quite easy to
distinguish, not like in other items, but
thank you very much for your help, you were right, i'm doing it now this
way and it works super:

protected void dataListRoleMembers_ItemCommand(object source,
DataListCommandEventArgs e)
{
string cmd = ((LinkButton)e.CommandSource).CommandName;

TextBox txtMember = (TextBox)(e.Item.FindControl("txtAddMember"));
string txt = txtMember.Text;

if (txtMember.Text.Length > 0 && cmd=="add")
{
try
{
....
}
....
}
}

Thanks one more time!
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,969
Messages
2,570,161
Members
46,709
Latest member
AustinMudi

Latest Threads

Top