Cannot put the text in input box in asp.net - c#

I am trying to make the input box show some text in the asp.net using c#, but after I run the code behind, nothing is displayed in the input box. The ui is RadNumericTextBox uiDistance. In class, I put this.uiDistance.Text = "123"; But in the webpage after run the code. I cannot see "123" is put in the uiDistance text box. How can I fix it?
Here is my aspx UsageControl2SubControl1.ascx
<%# Control Language="C#" AutoEventWireup="true" CodeBehind="UsageControl2SubControl1.ascx.cs" Inherits="WebControls.UsageControl2SubControl1" %>
<asp:HiddenField ID="uiRemoved" Value="false" runat="server" />
<asp:HiddenField ID="uiID" runat="server" />
<div class="form-group">
<div class="col-md-2 customColumnPadding">
<asp:UpdatePanel ID="UpdatePanel1" runat="server">
<ContentTemplate>
<telerik:RadTextBox ID="uiToLocation" runat="server" Width="100%" AutoPostBack="true"
OnTextChanged="uiToLocation_Leave" EmptyMessage="<%$ Resources:ResourceHKEx,Arrive_To %>" />
</ContentTemplate>
</asp:UpdatePanel>
</div>
<div class="col-md-2 customColumnPadding" id="uiColumnDistance" runat="server">
<telerik:RadNumericTextBox ID="uiDistance" runat="server" Width="100%" MinValue="0" NumberFormat-DecimalDigits="2" EmptyMessage="<%$ Resources:Resource,Distance %>" />
</div>
</div>
<div class="hr-line-dashed"></div>
And Here is my code behind: UsageControl2SubControl1.ascx.cs
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Telerik.Web.UI;
namespace WebControls
{
public partial class UsageControl2SubControl1 : System.Web.UI.UserControl
{
protected void Page_Load(object sender, EventArgs e)
{
if (Convert.ToBoolean(uiRemoved.Value))
{
this.Visible = false;
}
}
protected void uiAdd_Click(object sender, Telerik.Web.UI.ImageButtonClickEventArgs e)
{
}
protected void uiRemove_Click(object sender, Telerik.Web.UI.ImageButtonClickEventArgs e)
{
}
protected void RadComboBoxProduct_ItemsRequested(object sender, RadComboBoxItemsRequestedEventArgs e)
{
}
protected void uiAdd_Click1(object sender, ImageClickEventArgs e)
{
}
protected void uiRemove_Click1(object sender, ImageClickEventArgs e)
{
}
protected void uiToLocation_Leave(object sender, EventArgs e)
{
this.uiDistance.Text = "123";
}
}// end class
}// end namespace

Just to update your aspx code little bit
<asp:UpdatePanel ID="UpdatePanel1" runat="server">
<ContentTemplate>
<div class="form-group">
<div class="col-md-2 customColumnPadding">
<telerik:RadTextBox ID="uiToLocation" runat="server" Width="100%" AutoPostBack="true"
OnTextChanged="uiToLocation_Leave" EmptyMessage="<%$ Resources:ResourceHKEx,Arrive_To %>" />
</div>
<div class="col-md-2 customColumnPadding" id="uiColumnDistance" runat="server">
<telerik:RadNumericTextBox ID="uiDistance" runat="server" Width="100%" MinValue="0" NumberFormat-DecimalDigits="2" EmptyMessage="<%$ Resources:Resource,Distance %>" />
</div>
</div>
</ContentTemplate>
</asp:UpdatePanel>
As your textbox is only inside the update panel so, on post back only that portion is partially updated, you need to put RadNumericTextBox inside the update panel too.
Hope this will work.

You are using the wrong property. Use Value not Text
protected void uiToLocation_Leave(object sender, EventArgs e)
{
this.uiDistance.Value = "123";
}
As always, check the documentation. See: https://docs.telerik.com/devtools/aspnet-ajax/controls/numerictextbox/features/getting-and-setting-values

Your current code will works only when you tab out from uiToLocation textbox.
If you want to show it when page loads, just move your code in to Page_Load event instead uiToLocation_Leave.
protected void Page_Load(object sender, EventArgs e)
{
if (Convert.ToBoolean(uiRemoved.Value))
{
this.Visible = false;
}
this.uiDistance.Text = "123"; // it will assign when page loads.
}
If you want to load it only once when page loads, use IsPostaback, see below.
protected void Page_Load(object sender, EventArgs e)
{
if (Convert.ToBoolean(uiRemoved.Value))
{
this.Visible = false;
}
if (!IsPostBack)
{
this.uiDistance.Text = "123"; // it will assign only once when page loads.
}
}

IT seems you are using the wrong property to assign value to telerik Textbox.
Use .Value property as .Text property if for default aspx Textbox control
this.uiDistance.Value= "123"

Related

Classes and object in C# Asp.Net

i am trying to learn classes and objects in C#, i want to get the textbox value and show it in a label using classes and get set property.
i try the below process, but i will not showing/output anything.
index.aspx code
<%# Page Language="C#" AutoEventWireup="true" CodeBehind="Index.aspx.cs" Inherits="classes.Index" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:TextBox ID="fname" runat="server" /><br />
<asp:TextBox ID="lname" runat="server" /><br />
<asp:TextBox ID="password" runat="server" /><br />
<asp:Button Text="Submit" ID="submit" runat="server" OnClick="submit_Click" />
<br />
<br />
<br />
<br />
<asp:Label ID="FirstName" runat="server"></asp:Label>
</div>
</form>
</body>
</html>
Button click code
protected void submit_Click(object sender, EventArgs e)
{
basicinfo bn = new basicinfo();
FirstName.Text = bn.fname;
}
class
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace classes
{
public class basicinfo
{
public string fname;
public string last_name;
public string password;
public string Name
{
get{return fname;}
set{fname=value;}
}
}
}
Can someone tell me is this the wrong way? Also please provide reference of any helping material/Links/video tutorials course through which i can clear my basic classes, get set, objects, methods idea, i am heaving trouble to understand it.
Update
if this how it works
protected void submit_Click(object sender, EventArgs e)
{
basicinfo bn = new basicinfo();
bn.Name = fname.Text;
FirstName.Text =bn.Name;
}
then why should we use classes and get, set properties?
we can simply do like
protected void submit_Click(object sender, EventArgs e)
{
FirstName.Text = fname.Text;
}
You are trying to save the object value in the Label but Your object is empty it does not contain textbox value. Your code should be
protected void submit_Click(object sender, EventArgs e)
{
basicinfo bn = new basicinfo();
bn.fname= fname.Text; //textbox value to object
FirstName.Text = bn.fname; //object value to label
}

Multiview controls

I wrote the following code for multiview where I am using gridview and datalist:
<ContentPlaceHolderID="ContentPlaceHolder1">
<div class="alert alert-success" >
<div class="divbtn" style="text-align:right">
<asp:LinkButton ID="gridbtn" runat="server" CssClass="glyphicon glyphicon-th" OnClick="gridbtn_Click"></asp:LinkButton>
<asp:LinkButton ID="listbtn" runat="server" CssClass="glyphicon glyphicon-th-list" OnClick="listbtn_Click"></asp:LinkButton>
</div>
</div>
<asp:MultiView runat="server" ID="multiview" ActiveViewIndex="0">
<asp:View runat="server" ID="gridview">
<uc1:GridControl runat="server" ID="GridControl"/>
</asp:View>
<asp:View runat="server" ID="listview">
<uc1:Listing runat="server" ID="Listing" />
</asp:View>
</asp:MultiView>
</asp:Content>
I am using two link buttons to call their respective views by firing two separate events as follows.
protected void listbtn_Click(object sender, EventArgs e)
{
multiview.ActiveViewIndex = 1;
}
protected void gridbtn_Click(object sender, EventArgs e)
{
multiview.ActiveViewIndex = 0;
}
Suppose, my datalist (Index=1) is active on my page and if there is a post back it should still be showing the datalist but on postback it automatically switches back to grid view (Index=0). I really need help with this!
You can save the index to a session variable and then read it back on post back like this:
To save:
Session["index"] = index.ToString();
Read it on page load like this:
Index = Session["index"];
You will need the session variable to maintain state per user session. If you want to maintain state for the application then you have to use the application variable.
Hi add the following code in your page_load event.
if(!Page.IsPostBack)
{
multiview.ActiveViewIndex=0;
}
i think you are setting the multiview's active index to zero on every post back like follows
protected void Page_Load(object sender, EventArgs e)
{
multiview.ActiveViewIndex=0;
}
this will cause the multiview to set active index as 0 on every post back.To avoid this you have to set it as follows
protected void Page_Load(object sender, EventArgs e)
{
if(!Page.IsPostBack)
{
multiview.ActiveViewIndex=0;
}
}

Passing Value from UserControl to ParentPage control not working properly

I have create a photo gallery user control that show photographer in a fancy box.
I also use this control on several page to show page related photos. In hide photogallery user control if their are no photos for perticular page. For this i pass public event
public event SendMessageToThePageHandler showGallery;
to pass a boolean value to hide and show usercontrol on the page.
Page runs without any errors and show the gallery. But problem is with the Pager which doesn't work the way i am coded it. It generate NullReferenceException when i click on the page 2 or the gallery
I would appreeciate a more professional approach to this scenario in which i can pass passvalue to parent page correctly to hide/show correctly.
I am also using UpdatePanel in my usercontrol. Below is the sample code from Parent Page & User Control page
PageOne.aspx
<uc1:PhotoGallery ID="ucPhotoGallery" runat="server" />
CODE BEHIND
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
try
{
int _LangID = int.Parse(Helper.GetAppSettingValue("EnglishLanguageID"));
if (string.IsNullOrEmpty(Request["PID"]))
{
_LID = int.Parse(HttpContext.Current.Request.RequestContext.RouteData.Values["LID"].ToString());
_PID = int.Parse(HttpContext.Current.Request.RequestContext.RouteData.Values["PID"].ToString());
getPageDetails(_PID);
getPageSubMenus(_PID);
// WriteThisMessageToThePage1.sendMessageToThePage += delegate(string message)
ucPhotoGallery.showGallery += delegate(bool showControl)
{
bool bShowControl = showControl;
ucPhotoGallery.Visible = bShowControl;
};
}
else
{
Response.Write("Page not be found, Wrong URL");
}
}
catch (Exception ex)
{
}
}
}
Photo-Gallery.ascx
<%# Control Language="C#" AutoEventWireup="true" CodeFile="Photo-Gallery.ascx.cs" Inherits="Photo_Gallery" %>
<%# Register Src="~/en/UserControls/PagerControl.ascx" TagName="PagerControl" TagPrefix="uc1" %>
<div class="uc-gallery-wrapper">
<div class="page-title-side-wrapper"><h5><asp:Label ID="lblPageTitleSide" CssClass="lbl-page-title-side" runat="server" Text=" Gallery"></asp:Label></h5></div>
<asp:UpdatePanel ID="updPnlAlbums" runat="server" UpdateMode="Conditional">
<ContentTemplate>
<div class="rptAlbums-wrapper">
<asp:Repeater ID="rptAlbums" runat="server" >
<ItemTemplate>
<div class="uc-album-wrapper">
<div class="uc-album-icon"><asp:Image ID="imgAlbumIcon" CssClass="uc-album-img" ImageUrl='<%# getImage(Eval("AlbumIcon")) %>' AlternateText='<%# getTitle(Eval("AlbumName")) %>' runat="server" /></div>
<div class="uc-album-name">
<asp:HyperLink ID="hylnkAlbum" CssClass="fancybox-iframe" runat="server" NavigateUrl='<%# getAID(Eval("AlbumID")) %>'>
<asp:Label ID="lblAlbumName" runat="server" Text='<%# getTitle(Eval("AlbumName")) %>'></asp:Label>
</asp:HyperLink>
</div>
</div>
</ItemTemplate>
</asp:Repeater>
</div>
<div class="uc-gallery-pager-wrapper-o">
<div class="uc-pager-wrapper-i">
<uc1:PagerControl ID="PagerControl1" runat="server" CssClass="gold-pager" PageMode="LinkButton" />
<asp:UpdateProgress ID="UpdateProgress1" runat="server" AssociatedUpdatePanelID="updPnlAlbums" Visible="False">
<ProgressTemplate>
<div id="imgLoadingNewsList" class="uc-PagerLoading">
<asp:Image ID="imgLoading" runat="server" ImageUrl="~/Images/preloader-160x15.gif" Visible="false" AlternateText="loading" />
</div>
</ProgressTemplate>
</asp:UpdateProgress>
</div>
</div>
</ContentTemplate>
</asp:UpdatePanel>
<!-- UpdatePanel -->
</div>
CODE BEHIND
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Threading;
using System.Globalization;
using System.Data;
using CMS.SqlHelper;
using CMS.DataAccessLayer;
using System.Text;
public delegate void SendMessageToThePageHandler(bool showGallery);
public partial class Photo_Gallery : System.Web.UI.UserControl
{
int _PageID = 0;
public event SendMessageToThePageHandler showGallery;
protected void Page_Load(object sender, EventArgs e)
{
PagerControl1.PagerControl_PageIndexChanged += new EventHandler(PagerControl1_PagerControl_PageIndexChanged);
Page.MaintainScrollPositionOnPostBack = false;
if (!IsPostBack)
{
if (string.IsNullOrEmpty(Request["PID"]))
{
_PageID = int.Parse(HttpContext.Current.Request.RequestContext.RouteData.Values["PID"].ToString());
//_PageID = 3;
getAlbumByPageID(3);
}
else
{
Response.Write("Page not be found, Wrong URL");
}
}
}
public void getAlbumByPageID(int _PageID)
{
PagerControl1.PageSize = 2;
PagerControl1.DisplayEntriesCount = 5;
//Will show 2 links after ...
PagerControl1.EdgeEntriesCount = 0;
DataSet ds = DataProvider.GetAlbumByPageID(_PageID);
DataView dv = ds.Tables[0].DefaultView;
if (ds.Tables[0].Rows.Count > 0)
{
showGallery(true);
}
else
{
showGallery(false);
}
//pass the datatable and control to bind
PagerControl1.BindDataWithPaging(rptAlbums, dv.Table);
}
void PagerControl1_PagerControl_PageIndexChanged(object sender, EventArgs e)
{
_PageID = int.Parse(HttpContext.Current.Request.RequestContext.RouteData.Values["PID"].ToString());
getAlbumByPageID(_PageID);
}
}
WORK AROUND
I found a work around by wrapping my users control in a panel and hide/show panel if i have photos for that page or not. This is working fine but i still want to fix problem i have or even a better way of doing it.
<asp:Panel ID="pnl_uc_Gallery" runat="server" Visible="false">
// I have PUT all the USER CONTROL CODE In SIDE THIS BLOAK
</asp:Panel>
if (ds.Tables[0].Rows.Count > 0)
{
// showGallery(true);
pnl_uc_Gallery.Visible = true;
}
else
{
//showGallery(false);
pnl_uc_Gallery.Visible = false;
}
This code:
ucPhotoGallery.showGallery += delegate(bool showControl)
{
bool bShowControl = showControl;
ucPhotoGallery.Visible = bShowControl;
};
is in a !Page.IsPostback call; move it outside so that you are attaching to the event on every postback, not just the first one, or use a method as the event handler and set the method name in the markup. Either way, the issue is the event handler is established only on the first page load, not subsequent loads, and it needs to be done every time a request hits the server.

Uncaught Sys.InvalidOperationException: Sys.InvalidOperationException: Could not find UpdatePanel

I`m building a dashboard application using ASP.NET where users can change positions of the widgets; i used jquery sortables for that. The widgets are ascx (asp.net usercontrols) which are added dynamically to the page. Every event in the widget works fine on if the user have not changed the positions of the widgets but if the position is changed i get this error.
Uncaught Sys.InvalidOperationException: Sys.InvalidOperationException: Could not find UpdatePanel with ID 'xxx'. If it is being updated dynamically then it must be inside another UpdatePanel.
Here is the code of one of the widgets and user can add multiple instances of it.
<asp:UpdatePanel ID="UpdatePanel1" runat="server" >
<ContentTemplate>
<div class="setting" >
<asp:TextBox ID="txtwidgettitle" runat="server"></asp:TextBox>
<div id="settingfooter">
<asp:LinkButton ID="lnkbtnSave" runat="server" onclick="lnkbtnSave_Click">Save</asp:LinkButton>
<asp:LinkButton ID="lnkbtncancel" runat="server" CssClass="btn ui-state-default ui-corner-all">Cancel</asp:LinkButton>
</div>
</div>
</ContentTemplate>
<Triggers>
<asp:AsyncPostBackTrigger ControlID="lnkbtnSave" EventName="Click" />
</Triggers>
</asp:UpdatePanel>
<div class="pcontent">
<asp:Literal ID="ltrtwcontent" runat="server"></asp:Literal>
</div>
And the code behind
protected void Page_Load(object sender, EventArgs e)
{
ltrtwcontent.Text = jqPlotHelper.RenderChart(CurrentWidgetInstance.Id.ToString());
}
protected void lnkbtnSave_Click(object sender, EventArgs e)
{
DashboardServices d = new DashboardServices();
CurrentWidgetInstance.Title = txtwidgettitle.Text;
CurrentWidgetInstance.LastUpdate = DateTime.Now;
d.SaveOrUpdateWidgetInstance(CurrentWidgetInstance);
}
on the aspx page loading the controls i first have a container which is added dynamically and the container will add the the widget instances (the ascx controls)
Code on the page
protected void Page_Init(object sender, EventArgs e)
{
this.SetBasePageVAR(DashboredPageGuid);
if (this.UsrPage != null)
{
phltabs.Controls.Add(LoadDashboardTab());
}
}
public HtmlGenericControl LoadDashboardTab()
{
HtmlGenericControl mainList = new HtmlGenericControl("div");
mainList.Attributes["Id"] = "tabs";
foreach (WidgetInstance widgetInst in CurrentDashboardTab.WidgetInstances)
{
HtmlGenericControl headerList = new HtmlGenericControl("ul");
WidgetContainerBaseControl widgetContainer = LoadControl("~/Dashboard/WidgetContainer.ascx") as WidgetContainerBaseControl;
widgetContainer.SetControlVAR(widgetInst);
headerList.Controls.Add(widgetContainer);
mainList.Controls.Add(headerList);
}
return mainList;
}
and on WidgetContainer.ascx
protected void Page_Init(object sender, EventArgs e)
{
LoadWidgetInstance();
}
public void LoadWidgetInstance()
{
WidgetControl widget = LoadControl(CurrentWidgetInstance.Widget.Url) as WidgetControl;
widget.ID = "wid_" + CurrentWidgetInstance.Id;
this.phlcontent.Controls.Add(div);
}
try this: Add trigger Like this and Remove the one in Asps Page
ScriptManager sm = (ScriptManager)Page.Master.FindControl("ScriptManager1");
sm.RegisterPostBackControl(Button);

Running a C# and a Javascript function on an asp button control?

I can get both the Javascript and the C# function to work just fine.
However, my Javascript function runs before the C#.
How do I get it to run after the C# function??
Here is my code:
<script src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8/jquery-ui.min.js"></script>
<asp:UpdatePanel ID="UpdatePanel1" runat="server" UpdateMode="Conditional">
<ContentTemplate>
<asp:MultiView ID="MultiView1" runat="server" ActiveViewIndex="0">
<asp:View ID="View1" runat="server">
<div id="div2" style="height:70px; width:auto; text-align:center;">
<p><b>This is A View!!!</b></p>
<asp:Label ID="Label1" runat="server" Text="Label"></asp:Label>
</div>
<div id="div1">
<asp:Button ID="Button1" runat="server" Text="Button" onclick="Button1_Click"
OnClientClick="javascript:Highlit()" />
</div>
</asp:View>
</asp:MultiView>
<script type="text/javascript">
function Highlit()
{
$("#div2").effect("highlight", {}, 10000);
}
</script>
</ContentTemplate>
</asp:UpdatePanel>
Code behind:
namespace jQuery_Highlight.jQuery_Highlight
{
public partial class jQuery_HighlightUserControl : UserControl
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void Button1_Click(object sender, EventArgs e)
{
Label1.Text = "Changed";
}
}
}
Here is the code reflecting changes from the answers:
Code behind
namespace jQuery_Highlight.jQuery_Highlight
{
public partial class jQuery_HighlightUserControl : UserControl
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void Button1_Click(object sender, EventArgs e)
{
Label1.Text = "Changed";
ScriptManager.RegisterStartupScript(this, this.GetType(), "TEST", "Highlit();", true);
}
}
}
<script src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8/jquery-ui.min.js"></script>
<asp:UpdatePanel ID="UpdatePanel1" runat="server" UpdateMode="Conditional">
<ContentTemplate>
<asp:MultiView ID="MultiView1" runat="server" ActiveViewIndex="0">
<asp:View ID="View1" runat="server">
<div id="div2" style="height:70px; width:auto; text-align:center;">
<p><b>This is A View!!!</b></p>
<asp:Label ID="Label1" runat="server" Text="Label"></asp:Label>
</div>
<div id="div1">
<asp:Button ID="Button1" runat="server" Text="Button" onclick="Button1_Click" />
</div>
</asp:View>
</asp:MultiView>
</ContentTemplate>
</asp:UpdatePanel>
<script type="text/javascript">
function Highlit() {
$("#div2").effect("highlight", { color: "#9499FC" }, 10000);
}
</script>
The only way to get the javascript to run after is to add a script reference in your Button1_Click event.
Example Code for standard postback:
protected void Button1_Click(object sender, EventArgs e)
{
Label1.Text = "Changed";
Page.ClientScript.RegisterStartupScript(this.GetType(), "PostButton1_ClickScript", "Highlit();", true);
}
As noted by others, be sure to remove your OnClientClick event. Also, consider moving your "Highlit" script outside of the update panel.
Additionally, since you are in an update panel, you will need to use the following example code for a Partial Postback:
protected void Button1_Click(object sender, EventArgs e)
{
Label1.Text = "Changed";
ScriptManager.RegisterStartupScript(this, this.GetType(), "PostButton1_ClickScript", "Highlit();", true);
}
You have to register a ClientScript at the end of Button1_Click event
and remove OnClientClick="javascript:Highlit()"
protected void Button1_Click(object sender, EventArgs e)
{
//Do stuff
ScriptManager.RegisterStartupScript(this, this.GetType(), "ANYNAME", "javascript:Highlit();", true);
}
Remove the OnClientClick attribute, and add the call as a startup script, so that it runs after the page has loaded:
protected void Button1_Click(object sender, EventArgs e) {
Label1.Text = "Changed";
Page.ClientScript.RegisterStartupScript(this.GetType(), "start", "Highlit();", true);
}
Side note: When you use the OnClientClick attribute, the code should not start with javascript:. That's only used when you put script in a href attribute in a link.

Categories

Resources