Snackbar in ASP.NET - 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);
}

Related

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

Information disappears on button click

I have a ListView that has a FileUpload control and a button in each ListViewItem.
I have an OnClick event on my button where i try and pull information from the FileUpload control, but when I try to access the control all of the values that were set are gone (FileName etc).
What do I need to do differently here to access the information I just entered?
<asp:ListView ID="lv_Uploads" runat="server" OnItemDataBound="GetThumbs" EnableViewState="true" >
<LayoutTemplate>
<div id="itemPlaceholder" runat="server" />
</LayoutTemplate>
<ItemTemplate>
<div style="width:500px;>
<asp:FileUpload runat="server" ID="fu_Upload" />
<asp:Button ID="btn_Save" runat="server" Text="Save File" OnClick="SaveFile" />
<br />
</div>
</ItemTemplate>
</asp:ListView>
Code behind:
protected void SaveFile(object sender, EventArgs e)
{
//This always evaluates to an empty string...
string myFile = ((FileUpload)((Button)sender).Parent.FindControl("fu_Upload")).FileName;
}
I tested the code you provided for the aspx and the following as the code behind:
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
lv_Uploads.DataSource = data;
lv_Uploads.DataBind();
}
}
protected void SaveFile(object sender, EventArgs e)
{
//This always evaluates to an empty string...
string myFile = ((FileUpload)((Button)sender).Parent.FindControl("fu_Upload")).FileName;
}
protected void GetThumbs(object sender, ListViewItemEventArgs e)
{
}
protected IEnumerable<string> data = new string[] { "test1", "test2", "test3" };
The FileUpload control had data for me on PostBack.
Are you using an UpdatePanel around the ListView? FileUpload controls are not compatible with UpdatePanels.
See:
FileUpload control inside an UpdatePanel without refreshing the whole page?
and
http://msdn.microsoft.com/en-us/library/bb386454.aspx#UpdatePanelCompatibleControls
Is the ListView control being rebound before SaveFile is fired on PostBack? If so, it would wipe out any values the user entered.

ASP.Net dropdown control loses state after being set dynamically through javascript

I have an asp.net dropdownlist control. There are two ways it can be selected.
The first is through a button that sets the value in the drop-down list via javascript.
The second is by manually selecting the dropdownlist option.
Each of these methods work by themselves.
If I do the first followed by the second and then hit save - the value that is saved is the value set by the javascript. The manual selection did not have any effect.
Does anyone know why this is the case?
EDIT:
In the HTML Head section:
<script>
function Select(allocationId) {
document.getElementById('Accounts').value=allocationId;
}
</script>
In the HTML Body:
<asp:DropDownList ID="Accounts" runat="server"></asp:DropDownList>
<button onclick="Select(<%#"'" + DataBinder.Eval(Container.DataItem, "Associated_AccountId") + "'"%>)" type="button">Select</button>
<asp:Button ID="btn_SaveAndClose" runat="server" Text="Save and Close" OnClick="btn_SaveAndClose_Click"></asp:Button>
In the code behind:
protected void btn_SaveAndClose_Click(object sender, System.EventArgs e)
{
int id = Convert.ToInt32(this.Accounts.SelectedValue);
}
EDIT:
Funnily enough - when I use:
int id = Convert.ToInt32(Request.Form["Accounts"]);
it works. But I don't know why.
The most common mistake that would cause this is that you're likely populating or binding that DropDownList every Page_Load or Init, thus erasing whatever state you entered the page with. Be sure to do a (!IsPostBack) check before populating your DropDownList.
This worked for me: (try removing the !IsPostBack check and see if the behavior is similar to what you're seeing in your app)
page content
<asp:DropDownList ID="ddlTest" runat="server"></asp:DropDownList>
<button onclick="select(3);">Select Three</button>
<asp:Button ID="btnSave" runat="server" OnClick="btnSave_Click" Text="Save" />
<script type="text/javascript" language="javascript">
//<![CDATA[
function select(value) {
var ddlTest = document.getElementById('<%=ddlTest.ClientID%>');
for (var i = 0; i < ddlTest.options.length; i++) {
if (ddlTest.options[i].value == value) {
ddlTest.selectedIndex = i;
return;
}
}
}
//]]>
</script>
<asp:Label ID="lblResult" runat="server"></asp:Label>
Code Behind
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
PopulateDropDown();
}
protected void btnSave_Click(object sender, EventArgs e)
{
lblResult.Text = ddlTest.SelectedValue;
}
void PopulateDropDown()
{
Dictionary<int, string> data = new Dictionary<int, string>();
data.Add(1, "One");
data.Add(2, "Two");
data.Add(3, "Three");
ddlTest.DataSource = data;
ddlTest.DataTextField = "Value";
ddlTest.DataValueField = "Key";
ddlTest.DataBind();
}

Setting viewstate on postback

I am trying to set a ViewState-variable when a button is pressed, but it only works the second time I click the button. Here is the code-behind:
protected void Page_Load(object sender, EventArgs e)
{
if (Page.IsPostBack)
{
lblInfo.InnerText = String.Format("Hello {0} at {1}!", YourName, DateTime.Now.ToLongTimeString());
}
}
private string YourName
{
get { return (string)ViewState["YourName"]; }
set { ViewState["YourName"] = value; }
}
protected void btnSubmit_Click(object sender, EventArgs e)
{
YourName = txtName.Text;
}
Is there something I am missing? Here is the form-part of the design-file, very basic just as a POC:
<form id="form1" runat="server">
<div>
Enter your name: <asp:TextBox runat="server" ID="txtName"></asp:TextBox>
<asp:Button runat="server" ID="btnSubmit" Text="OK" onclick="btnSubmit_Click" />
<hr />
<label id="lblInfo" runat="server"></label>
</div>
</form>
PS: The sample is very simplified, "use txtName.Text instead of ViewState" is not the correct answer, I need the info to be in ViewState.
Page_Load fires before btnSubmit_Click.
If you want to do something after your postback events have fired use Page_PreRender.
//this will work because YourName has now been set by the click event
protected void Page_PreRender(object sender, EventArgs e)
{
if (Page.IsPostBack)
lblInfo.InnerText = String.Format("Hello {0} at {1}!", YourName, DateTime.Now.ToLongTimeString());
}
The basic order goes:
Page init fires (init cannot access ViewState)
ViewState is read
Page load fires
Any events fire
PreRender fires
Page renders

Resources