asp.net repeater in update panel databind outside page_load - asp.net

I have repeater in updatePanel asp.net. It works fine when I run databind() in Page_load method. But when databind() is called by some event outside Page_load, repeater cleared. Databind() does not work in this case! What can be reason for this?
this is code ...
this works:
protected void Page_Load(object sender, EventArgs e)
{
........
populateCalendar(Int32.Parse(DDL_YearsList.SelectedValue), Int32.Parse(DDL_MonthsList.SelectedValue), Int32.Parse(DDL_EmployeesList.SelectedValue));
}
private void populateCalendar(int year, int month, int idEmploee)
{
.......
monthShower.DataSource = listWeeks;
monthShower.DataBind();
}
protected void DDL_EmployeesList_SelectedIndexChanged(object sender, EventArgs e)
{
//populateCalendar(Int32.Parse(DDL_YearsList.SelectedValue), Int32.Parse(DDL_MonthsList.SelectedValue), Int32.Parse(DDL_EmployeesList.SelectedValue));
}
this does not work, when DDL_EmployeesList_SelectedIndexChanged fired:
protected void Page_Load(object sender, EventArgs e)
{
........
// populateCalendar(Int32.Parse(DDL_YearsList.SelectedValue), Int32.Parse(DDL_MonthsList.SelectedValue), Int32.Parse(DDL_EmployeesList.SelectedValue));
}
private void populateCalendar(int year, int month, int idEmploee)
{
.......
monthShower.DataSource = listWeeks;
monthShower.DataBind();
}
protected void DDL_EmployeesList_SelectedIndexChanged(object sender, EventArgs e)
{
populateCalendar(Int32.Parse(DDL_YearsList.SelectedValue), Int32.Parse(DDL_MonthsList.SelectedValue), Int32.Parse(DDL_EmployeesList.SelectedValue));
}
<asp:Repeater id ="monthShower" runat ="server"> <ItemTemplate> <custom:DayID="Day1" runat ="server" TblDay =<%# DataBinder.Eval(Container.DataItem, "Monday") %>></custom:Day> </ItemTemplate> </asp:Repeater>

So i did a small test and posted the code
Html:
<div id="test">
<asp:DropDownList runat="server" ID="DropDownList1" AutoPostBack="true" OnSelectedIndexChanged="DropDownList1_SelectedIndexChanged"></asp:DropDownList>
<asp:UpdatePanel runat="server">
<ContentTemplate>
<table>
<asp:Repeater runat="server" ID="repTeste" OnItemDataBound="repTeste_ItemDataBound">
<ItemTemplate>
<tr>
<td runat="server" id="tdTeste">
</td>
</tr>
</ItemTemplate>
</asp:Repeater>
</table>
</ContentTemplate>
</asp:UpdatePanel>
</div>
C# - I used pop() in my pageLoad just to populate the ddl:
protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)
{
populateCalendar(DropDownList1.SelectedValue, 2, 3);
}
private void populateCalendar(String year, int month, int idEmploee)
{
List<String> lis = new List<String>();
lis.Add(year);
repTeste.DataSource = lis;
repTeste.DataBind();
}
private void pop()
{
ListItem li = new ListItem("1", "1");
li.Attributes.Add("title", "1");
DropDownList1.Items.Add(li);
li = new ListItem("2", "2");
li.Attributes.Add("t2itle", "2");
DropDownList1.Items.Add(li);
li = new ListItem("3", "3");
li.Attributes.Add("ti3tle", "3");
DropDownList1.Items.Add(li);
}
protected void repTeste_ItemDataBound(object sender, RepeaterItemEventArgs e)
{
String inte = (String)e.Item.DataItem;
HtmlTableCell td = (HtmlTableCell)e.Item.FindControl("tdTeste");
td.InnerText = inte;
}
it updates correctly.
Since you didn't post your html and the fact that someone deleted my post, i posted my code here for you, you can use it to compare it or you can post your Html and ill give it a look.

Related

Web Form User Control Event, needs to be added after page loads

My application consists of a web form that someone may be pulling some information in. When that occurs, I'm loading a user control more than once, based on content, that has an ImageButton on it.
Since this is being loaded after page is already loaded, how can I get the click events to work properly. Since click events are required to be set during page_load.
Example Scenario:
Main.aspx
<form id="form1" runat="server">
<div>
<asp:Button ID="clicker" runat="server" Text="Click Me" />
<asp:PlaceHolder ID="PHwfuc" runat="server"></asp:PlaceHolder>
<asp:Label runat="server" ID="ResponseMessage"></asp:Label>
</div>
</form>
Main.aspx.cs
protected void Page_Load(object sender, EventArgs e)
{
clicker.Click += new EventHandler(this.ButClick);
}
protected void ButClick(object sender, EventArgs e)
{
PlaceHolder placeHolder = new PlaceHolder();
for (int i = 0; i < 2; i++)
{
WFUC1 test = LoadControl("~/WebFormUserControl/WFUC1.ascx") as WFUC1;
test.Ident = i;
placeHolder.Controls.Add(test);
}
PHwfuc.Controls.Add(placeHolder);
}
WFUC1.ascx
<asp:PlaceHolder runat="server" ID="DelAddrBtn"></asp:PlaceHolder>
<asp:Label runat="server" ID="ResponseMessage"></asp:Label>
<br />
WFUC1.ascx.cs
public WFUC1()
{
TrashIcon = new ImageButton
{
AlternateText = "Delete Address",
ImageUrl = "/images/trash.png",
ToolTip = "Delete Address",
};
TrashIcon.Style.Add("cursor", "pointer");
TrashIcon.Style.Add("width", "24px");
}
private ImageButton TrashIcon { get; set; }
public int Ident { get; set; }
protected void Page_Load(object sender, EventArgs e)
{
TrashIcon.ID = $"Delete_{Ident}";
TrashIcon.Click += new ImageClickEventHandler(this.TrashIcon_Click);
DelAddrBtn.Controls.Add(TrashIcon);
}
protected void TrashIcon_Click(object sender, ImageClickEventArgs e)
{
ResponseMessage.Text = $"Use Control Got it. {Ident}";
}
EDIT For Rango
WFUC1.ascx
<asp:ImageButton runat="server" ID="TrashIcon" ImageUrl = "/images/trash.png" ToolTip = "Delete Address" OnClick="TrashIcon_Click" />
<asp:Label runat="server" ID="ResponseMessage"></asp:Label>
<br />
WFUC1.ascx.cs
public partial class WFUC1 : System.Web.UI.UserControl
{
public int Ident { get; set; }
protected void TrashIcon_Click(object sender, ImageClickEventArgs e)
{
ResponseMessage.Text = $"Use Control Got it. {Ident}";
}
}
Seems, I have to reload all the controls on the main again to get the click event to execute. I accidentally made this work.
Below Project Visual Studio 2017 - No binaries, except for one image and the rest is only project code.
Main.aspx
<form id="form1" runat="server">
<asp:Button ID="clicker" runat="server" Text="Click Me" />
<asp:PlaceHolder ID="PHwfuc" runat="server"></asp:PlaceHolder>
<asp:Label runat="server" ID="ResponseMessage"></asp:Label>
</form>
Main.aspx.cs
protected void Page_Load(object sender, EventArgs e)
{
clicker.Click += new EventHandler(this.ButClick);
if(ViewState["ButClick"] != null)
LoadData();
}
protected void ButClick(object sender, EventArgs e)
{
LoadData();
}
private void LoadData()
{
PlaceHolder placeHolder = new PlaceHolder();
for (int i = 0; i < 2; i++)
{
WFUC1 test = LoadControl("~/WebFormUserControl/WFUC1.ascx") as WFUC1;
test.Ident = i;
placeHolder.Controls.Add(test);
}
PHwfuc.Controls.Add(placeHolder);
ViewState["ButClick"] = true;
}
WFUC1.ascx
<asp:ImageButton runat="server" ID="TrashIcon" ImageUrl = "/images/trash.png" ToolTip = "Delete Address" OnClick="TrashIcon_Click" />
<br />
<asp:Label runat="server" ID="ResponseMessage"></asp:Label>
WFUC1.ascx
public int Ident { get; set; }
public void TrashIcon_Click(object sender, ImageClickEventArgs e)
{
ResponseMessage.Text = $"Use Control Got it. {Ident}";
}

asp.net button in ITemplate doesn't fire Repeater ItemCommand event

i am a complete asp.net noob and the solution could be something very simple.
i have found, read and tried many answers to questions very similar to my question, but nothing works. i hope to find some help here.
this works perfectly with no problem:
<asp:Repeater ID="Repeater1" runat="server" onitemcommand="Repeater1_ItemCommand">
<ItemTemplate>
<asp:Button ID="Button1" runat="server" Text='<%# (Container.DataItem as Choice).description %>' CommandName="Choice" CommandArgument='<%# (Container.DataItem as Choice).id %>'/>
<br />
</ItemTemplate>
</asp:Repeater>
code behind:
void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
List<Choice> choiceList = new List<Choice>();
// ... code to fill the list ...
Repeater1.DataSource = choiceList;
Repeater1.DataBind();
}
}
void Repeater1_ItemCommand(object source, RepeaterCommandEventArgs e)
{
int idx = int.Parse( e.CommandArgument.ToString() );
// this function is called
}
but if i use ITemplate it doesn't work:
<asp:Repeater ID="Repeater1" runat="server" onitemcommand="Repeater1_ItemCommand">
</asp:Repeater>
code behind:
public class MyButtonTemplate : System.Web.UI.ITemplate
{
public void InstantiateIn(System.Web.UI.Control container)
{
Button button = new Button();
button.CommandName = "choice";
button.DataBinding += new EventHandler(Button_DataBinding);
container.Controls.Add(button);
container.Controls.Add(new LiteralControl("<br />"));
}
}
static void Button_DataBinding(object sender, System.EventArgs e)
{
Button button = (Button)sender;
RepeaterItem repeaterItem = (RepeaterItem)button.NamingContainer;
button.ID = "button" + (repeaterItem.DataItem as Choice).id.ToString();
button.CommandArgument = (repeaterItem.DataItem as Choice).id.ToString();
button.Text = (repeaterItem.DataItem as Choice).description;
}
void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
List<Choice> choiceList = new List<Choice>();
// ... code to fill the list ...
Repeater1.ItemTemplate = new MyButtonTemplate();
Repeater1.DataSource = choiceList;
Repeater1.DataBind();
}
}
void Repeater1_ItemCommand(object source, RepeaterCommandEventArgs e)
{
int idx = int.Parse( e.CommandArgument.ToString() );
// this function is NOT called
}
the buttons are displayed, but the event is not fired.
i have already tried saving a delegate in MyButtonTemplate and assigning the button click event - it does not work.
thank you!

NullException error in image control with UpdatePanel control in asp.net

when i use image control with updatepanel in asp.net, compiler gives an error : NullReference exception,
please any body help me. so what should be done to avoid such problem?
<asp:UpdatePanel ID="UpdatePanel1" runat="server">
<ContentTemplate>
<div>
<asp:AsyncFileUpload ID="flduserphoto" runat="server"
OnClientUploadComplete="OnClientAsyncFileUploadComplete"
OnUploadedComplete="OnAsyncFileUploadComplete" Width="374px" />
<asp:Image runat="server" ID="imgPhoto" Width="150px" />
</div>
</ContentTemplate>
</UpdatePanel>
code file is,
public partial class Registration_frmUserRegistration : System.Web.UI.Page
{
DataTable dt;
#region FileUploadControl Section
protected void OnAsyncFileUploadComplete(object sender, AsyncFileUploadEventArgs e)
{
if (flduserphoto.FileBytes != null)
{
lblgender.Text = "asdf";
Context.Session.Add("SessionImage", flduserphoto.FileBytes);
}
}
#endregion
protected void Page_Load(object sender, EventArgs e)
{
}
protected void btnSave_Click(object sender, EventArgs e)
{
BALUserAddress objUserAddress = new BALUserAddress();
objUserAddress.UserType = ddlusertype.Text;
byte[]imageByte = new byte[flduserphoto.PostedFile.ContentLength];
objUserAddress.ProfilePicture=imageByte;
objUserAddress.ParentID = "0";
objUserAddress.RelationWith="Self";
objUserAddress.RegistrationDateTime= DateTime.Now;
string msg = objUserAddress.SaveUserDetails();
lblMsg.Text=msg;
mpMsg.Show();
}
}
this is my code file please check it
Try this one in form tag
<form id="form1" enctype="multipart/form-data" method="post" runat="server">

C# - Event handler for dynamic buttons

I have a textbox and submit button created using the design mode.
When the submit button is pressed, it will retrieve the user input from the textbox and then make a query to my database.
It will then display a list of dynamic buttons according to the information retrieved from my database.
However, the event handler for the buttons does not fire when clicked. I guess my problem is the postback but I cannot create those buttons in page_load etc. because I need to get the user input (from the textbox when submit button is pressed) before i can load the buttons.
How can i solve this problem?
Thank you.
Edit (codes):
protected void subBtn_Click(object sender, EventArgs e)
{
//database setup codes
.......
while (reader.Read())
{
Button detailsBtn = new Button();
detailsBtn.Text = reader["fName"].ToString();
//doesn't fire
detailsBtn.Click += new EventHandler(detailsBtn_Click);
memPanel.Controls.Add(detailsBtn);
}
}
Main problem is Postback regenerate dynamic controls on each postback if those controls does not exists.
For quick demo see this code
ASPX CODE
<form id="form1" runat="server">
<asp:Button ID="Button1" runat="server" Text="Button" onclick="Button1_Click" />
<asp:Panel ID="pnl" runat="server"></asp:Panel>
</form>
ASPX.CS CODE
protected void Page_Load(object sender, EventArgs e)
{
if(IsPostBack)
{
generate();
}
}
public void generate()
{
if (!pnl.HasControls())
{
for (int i = 0; i < 4; i++)
{
Button detailsBtn = new Button();
detailsBtn.Text = "fName" + i.ToString();
detailsBtn.ID = i.ToString();
detailsBtn.Click += new EventHandler(detailsBtn_Click);
pnl.Controls.Add(detailsBtn);
}
}
}
protected void Button1_Click(object sender, EventArgs e)
{
generate();
}
protected void detailsBtn_Click(object sender, EventArgs e)
{
}
Sound to me like you could easily refactor your page to use a simple <asp:Repeater runat="server" ..></asp:Repeater> instead of dynamically adding controls to a Panel.
Here is a very simple complete sample:
RepeaterTest.aspx
<asp:Content ID="Content2" ContentPlaceHolderID="MainContent" runat="Server">
<asp:TextBox ID="theTextBox" runat="server"></asp:TextBox>
<asp:Button ID="theButton" runat="server" OnClick="theButton_Click" Text="Click me" />
<asp:Repeater ID="test" runat="server">
<ItemTemplate>
<asp:Button ID="theRepeaterButton" runat="server" Text='<%# Eval("fName") %>' OnClick="theRepeaterButton_Click" />
</ItemTemplate>
</asp:Repeater>
</asp:Content>
RepeaterTest.aspx.cs
public partial class RepeaterTest : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void theButton_Click(object sender, EventArgs e)
{
string filter = theTextBox.Text;
// below row simulates fetching data using the filter text in the text box
var data = Enumerable.Range(0, 20).Select(i => new { fName = filter + " " + i });
test.DataSource = data;
test.DataBind();
}
protected void theRepeaterButton_Click(object sender, EventArgs e)
{
var button = (Button)sender;
// do something here based on text/commandname/commandargument etc of the button
}
}

button events not fire in asp.net

The if (!Page.IsPostBack) is always false went the page loads after i click a linkbutton and it never goes into the linkbutton event. Desperately need help! Googled as much as I can. I am kinda new to asp
This is the code that i have in server:
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
SetDefaultView();
}
}
private void SetDefaultView()
{
MultiView1.ActiveViewIndex = 0;
}
protected void LinkButton1_Click(object sender, EventArgs e)
{
MultiView1.ActiveViewIndex = 0;
}
protected void LinkButton2_Click(object sender, EventArgs e)
{
MultiView1.ActiveViewIndex = 1;
}
// and below..
<td>
<asp:LinkButton ID="LinkButton1" runat="server"
onclick="LinkButton1_Click">Tab1</asp:LinkButton>
</td>
<td>
<asp:LinkButton ID="LinkButton2" runat="server" onclick="LinkButton2_Click">Tab2</asp:LinkButton>
</td>
Is the code part of a dynamically loaded UserControl? If so, in what stage of the asp.net lifecycle are you adding the UserControl?
If that is not the case, how do you access the Page?

Resources