NullException error in image control with UpdatePanel control in asp.net - 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">

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}";
}

Snackbar in ASP.NET

I am using this code from w3schools:
TryIt
How can i integrate it with asp:LinkButton or asp:Button using OnClientClick, while onClick is executing the server code.
Almost a year late to the party, but I've just implemented the same snackbar.
It needs an UpdatePanel and you need to register a client script block on your event handler:
<asp:UpdatePanel runat="server" ID="UpdatePanel1">
<ContentTemplate>
<div>
<asp:Button runat="server" ID="ShowSnackbar" Text="Show Snackbar" OnClick="ShowSnackbar_Click" />
</div>
<div id="snackbar">
<asp:Label runat="server" ID="Snack" />
</div>
</ContentTemplate>
</asp:UpdatePanel>
The codebehind was tricky but it works. On page load, create a string that contains the javascript, then use that string value to register your script block...
private string snackbarScript;
protected void Page_Load(object sender, EventArgs e)
{
snackbarScript = GenerateSnackbarJS();
}
private string GenerateSnackbarJS()
{
var sb = new StringBuilder();
sb.AppendLine("var x = document.getElementById('snackbar');");
sb.AppendLine("x.className = 'show';");
sb.AppendLine("setTimeout(function(){ x.className = x.className.replace('show', ''); }, 3000);");
return sb.ToString();
}
protected void ShowSnackbar_Click(object sender, EventArgs e)
{
Snack.Text = "Here's the snackbar";
ScriptManager.RegisterClientScriptBlock(this.Page, this.Page.GetType(), "snackbar", snackbarScript, true);
}

asp.net repeater in update panel databind outside page_load

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.

Calling method in parent from user control

For some business related reasons I made a wizard navigation user control. Pretty simple: Next/Previous/Finish buttons.
Each of the parent pages that use this nav user control have a SaveData function, which saves the data and does a bunch of other stuff.
When the user clicks Next/Previous/Finish I want to call the parent's SaveData function before redirecting to the other page. How should I do this or can you recommend a better way (code examples if possible please)?
Thanks in advance!
UserControl should not call Parent's function. It is not a good design.
Instead, you want to bubble up the event from UserControl to the Parent page.
Note: my project's namespace is DemoWebForm.
MyUserControl.ascx
<%# Control Language="C#" AutoEventWireup="true"
CodeBehind="MyUserControl.ascx.cs"
Inherits="DemoWebForm.MyUserControl" %>
<asp:Button runat="server" ID="NextButton"
OnClick="NextButton_Click" Text="Next" />
<asp:Button runat="server" ID="PreviousButton"
OnClick="PreviousButtonn_Click" Text="Previous" />
<asp:Button runat="server" ID="FinishButton"
OnClick="FinishButton_Click" Text="Finish" />
MyUserControl.ascx.cs
public partial class MyUserControl : System.Web.UI.UserControl
{
public event ClickEventHandler NextClicked;
public event ClickEventHandler PreviousClicked;
public event ClickEventHandler FinishClicked;
protected void NextButton_Click(object sender, EventArgs e)
{
if (NextClicked != null)
{
NextClicked(sender, e);
}
}
protected void PreviousButtonn_Click(object sender, EventArgs e)
{
if (PreviousClicked != null)
{
PreviousClicked(sender, e);
}
}
protected void FinishButton_Click(object sender, EventArgs e)
{
if (FinishClicked != null)
{
FinishClicked(sender, e);
}
}
}
Parent.aspx
<%# Page Language="C#" AutoEventWireup="true" CodeBehind="Parent.aspx.cs"
Inherits="DemoWebForm.Parent" %>
<%# Register Src="MyUserControl.ascx" TagName="MyUserControl" TagPrefix="uc1" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<uc1:MyUserControl ID="MyUserControl1" runat="server"
OnNextClicked="MyUserControl1_NextClicked"
OnPreviousClicked="MyUserControl1_PreviousClicked"
OnFinishClicked="MyUserControl1_FinishClicked" />
<asp:Literal runat="server" ID="MessageLiteral" />
</form>
</body>
</html>
Parent.aspx.cs
public partial class Parent : System.Web.UI.Page
{
protected void MyUserControl1_NextClicked(object sender,EventArgs e)
{
MessageLiteral.Text = "Next button was clicked";
}
protected void MyUserControl1_PreviousClicked(object sender, EventArgs e)
{
MessageLiteral.Text = "Previous button was clicked";
}
protected void MyUserControl1_FinishClicked(object sender, EventArgs e)
{
MessageLiteral.Text = "Finish button was clicked";
}
}
you only need the delegate:
public delegate void ClickEventHandler(object sender, EventArgs e);
public event ClickEventHandler NextClicked;

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
}
}

Resources