ASP.NET Passing variable from .aspx page to UserControl - c#

I have a usercontrol that I want to pass a value to from my .aspx page. I've setup a property in the usercontrol to set to the value I need from the page but the value is always null.
Here is my control code in the .aspx page,
<tcs:SubmitDataDiscrepancy runat="server" ID="SubmitDataDiscrepancy" EntityNameProp='<%# Bind("Association_Name") %>'/>
the .ascx code,
<div style="text-align:right;">
<asp:LinkButton ID="ReportLink" runat="server" Text="Report data discrepancy"></asp:LinkButton>
<asp:Panel ID="ReportPanel" runat="server" CssClass="modalPopup" style="width:auto;">
<div id="PopHeader" style="background-color: black; color: white; height: auto;">
Report discrepancy
<div style="float: right;">
<asp:LinkButton runat="server" ID="AssociationCancelTextButton" CausesValidation="False" Font-Underline="false"
CssClass="glyphicon glyphicon-remove white" ToolTip="Close" />
</div>
</div>
<div style="margin:10px;">
<div>
Submit change request for: <asp:Label ID="EntityName" runat="server" />
</div>
<div>
<textarea id="reportTextArea" runat="server" class="form-control" style="height: 100px; margin-bottom:10px; width: 100%;"></textarea>
<button id="reportSubmitButton" runat="server" class="btn btn-primary" type="submit">Submit</button>
</div>
</div>
and the .ascx.cs page,
public partial class SubmitDataDiscrepancy : System.Web.UI.UserControl
{
public string EntityNameProp { get; set; }
protected void Page_Load(object sender, EventArgs e)
{
EntityName.Text = EntityNameProp;
}
}
Why am I not getting the value I'm expecting from the .aspx page?

All variables are disposed at the end of the page's lifecycle, that's the stateless nature of HTTP. So you need a way to persist your property. You could for example use ViewState, Session or a HiddenField (Other ways).
In this case it makes sense to simply use the Label.Text:
public partial class SubmitDataDiscrepancy : System.Web.UI.UserControl
{
public string EntityNameProp {
get { return EntityName.Text; }
set{ EntityName.Text = value; }
}
}

Related

Populate Listview without DataSource/Table?

Just for background: So Im trying to create an interface for users to check-in. The concept is simple:A Listview where each item holds an image, name, some info, and a button to the right that says check-in (That they'd press).
This interface is on a webpage (.aspx) with an .aspx.cs codefile.
I've created my ListView & set templates
<asp:ListView
ID="lvInstructors"
runat="server"
AutoGenerateColumns="False"
ShowRegularGridWhenEmpty="False"
EmptyDataText="No Sessions to Display."
OnRowDataBound="lvDataBound"
OnRowCommand="lvCommand"
Visible="true">
<LayoutTemplate>
<div class="container" id="mainContent">
<asp:PlaceHolder ID="itemPlaceHolder" runat="server" />
</div>
</LayoutTemplate>
<ItemTemplate>
<div class="row instructorItem">
<div class="col-2 sessionStartTimeDiv">
<p class="sessionStartTime"></p>
</div>
<div class="col-2 instructorHeadshotDiv">
<asp:Image class="instructorHeadshot" runat="server" src="" />
</div>
<div class="col-5 sessionInfoDiv">
<h3 class="instructorName"></h3>
<p class="sessionInfo"></p>
</div>
<div class="col-3 checkInBtnDiv">
<asp:Button class="checkInBtn" OnClick="CheckInBtn_Click" ID="checkInBtn" runat="server" Text="CHECK-IN" />
</div>
</div>
</ItemTemplate>
<EmptyDataTemplate>No Sessions to Display</EmptyDataTemplate>
</asp:ListView>
My issue is, I don't want to link this ListView to a database, source, or table (Is that even possible)
Below are the variables in .aspx.cs that I'd like to populate my ListView Items with, but Im not sure how to go about doing do, especially when it comes to creating a new ListView Item per each for loop. Any suggestions? Thanks Alot!
foreach (Session S in UpcomingSessions)
{
foreach(Enrollment I in S.Instructors())
{
SessionName = S.Name;
SessionStartTime = S.FirstDateTime().ToShortTimeString();
InstructorName = I.FirstName + " " + I.LastName;
SessionRoom = S.Room.ToString();
}
}
Try like this
public class Instructors{
public string SessionName{get;set;}
public DateTime SessionStartTime {get;set;}
public string InstructorName {get;set;}
public string SessionRoom {get;set;}
}
List<Instructors> InstructorsLst=new List<Instructors>();
foreach (Session S in UpcomingSessions)
{
foreach(Enrollment I in S.Instructors())
{
Instructors inst=new Instructors();
inst.SessionName = S.Name;
inst.SessionStartTime = S.FirstDateTime().ToShortTimeString();
inst.InstructorName = I.FirstName + " " + I.LastName;
inst.SessionRoom = S.Room.ToString();
InstructorsLst.Add(inst);
}
}
lvInstructors.DataSrouce = InstructorsLst;
lvInstructors.DataBind();

ModalPopUp as User Control ASP.NET C#

Im trying build a ModalPopUp as Control. Its have theses controls:
TextBox- placeholder for filter
Button - Search Button
Button - Cancel Button
GridView - To show results
Screen of Search
<ajax:toolkitscriptmanager id="searchPopUp" runat="server"></ajax:toolkitscriptmanager>
<asp:Panel
BackColor="White"
ID="searchPanel"
CssClass="modalPopup"
runat="server"
Style="display: table">
<div class="myContainer">
<uc1:ScreenSearch
runat="server"
ID="mySearch" />
<asp:Button ID="btnToHide" runat="server" Text="Tohide" Style="display: none" />
<asp:Button ID="btnToShow" runat="server" Text="ToShow" Style="display: none" />
</div>
</asp:Panel>
<ajax:ModalPopupExtender
ID="ModalPopUpSearch"
runat="server"
TargetControlID="btnToShow"
PopupControlID="searchPanel"
CancelControlID="btnToHide"
DropShadow="true"
BackgroundCssClass="modalBackground">
</ajax:ModalPopupExtender>
code behind of : uc1:ScreenSearch
protected void Page_Load(object sender, EventArgs e){...}
protected void fillGridView()
{
myDao dao = new myDao();
DataSet ds = new DataSet();
ds = dao.retornarPesquisa(txtFilter.Text); //return data source
DataTable dt = new DataTable();
gv.DataSource = ds;
gv.DataBind();
}
uc1:ScreenSearch is my control that contain a TextBox, Button(perform search calling the method: fillGridView()) and GridView.
When I try perform the search click Binding the GridView. What the best way to get results in this GridView of my User Control?
You haven't posted any of your code so it's hard to tell why it's not working.Below is a working example which displays a Bootstrap modal popup -> allows a user to search -> displays the results in a GridView inside the modal popup:
Code behind:
public class Person
{
public string Name { get; set; }
public string Surname { get; set; }
}
public partial class ModalPopupFromGridView : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void btnSearch_Click(object sender, EventArgs e)
{
//Use txtSearch.Text to lookup the data you want to bind to the GridView, mine is hardcoded for the sake of simplicity
var p1 = new Person { Name = "Name 1", Surname = "Surname 1" };
var p2 = new Person { Name = "Name 2", Surname = "Surname 2" };
GridView1.DataSource = new List<Person> { p1, p2 };
GridView1.DataBind();
ScriptManager.RegisterStartupScript(this, this.GetType(), "myModal", "showPopup();", true);
}
}
.ASPX:
<head runat="server">
<title></title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.3/jquery.min.js"></script>
<script src="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>
<link rel="stylesheet" href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" />
<script type="text/javascript">
//It'svery important that showPopup() is outside of jQuery document load event
function showPopup() {
$('#myModal').modal('show');
}
$(function () {
$(".show").click(function () {
showPopup();
});
});
</script>
</head>
<body>
<form id="form1" runat="server">
Show Popup
<div id="myModal" class="modal fade">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
<h4 class="modal-title" id="myModalLabel">Details</h4>
</div>
<div class="modal-body">
<asp:TextBox ID="txtSearch" runat="server">
</asp:TextBox><asp:Button ID="btnSearch" runat="server" Text="Search" OnClick="btnSearch_Click" />
<br /><br />
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="false">
<Columns>
<asp:BoundField DataField="Name" HeaderText="Name" />
<asp:BoundField DataField="Surname" HeaderText="Surname" />
<asp:TemplateField HeaderText="User Details">
<ItemTemplate>
<a class="details" href="#" data-name='<%# Eval("Name") %>' data-surname='<%# Eval("Surname") %>'>Details</a>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-primary" data-dismiss="modal">Close</button>
</div>
</div>
</div>
</div>
</form>
</body>
Output:
Check if the search buttons autopostback is set to true. Also you will get the event of search button click in gridview_itemchanged event as the search button is inside gridview control. Hope that will work

Textchange event not working

I am doing a preview of what I am currently typing in a web page using ASP.NET. What I am trying to achieve is that whenever I type or change text in the textbox, the <h3> or label element will also change and always copy what the textbox value is without refreshing the browser. Unfortunately I cannot make it work. Here is what I tried.
.ASPX
<div class="Width960px MarginLeftAuto MarginRightAuto MarginTop10px">
<div class="Padding10px">
<h1 class="Margin0px">Preview</h1>
<hr />
<p></p>
<h3 id="NewsTitlePreview" class="TextAlignCenter" runat="server">Title</h3>
<h5 id="NewsContentPreview" class="TextIndent50px TextAlignJustify" runat="server">Content</h5>
</div>
</div>
<div class="Width960px MarginLeftAuto MarginRightAuto MarginTop10px">
Title
<asp:TextBox ID="Titletxt" runat="server" OnTextChanged="Titletxt_TextChanged"></asp:TextBox>
Content
<asp:TextBox ID="Contenttxt" runat="server" onchange="Contenttxt_TextChanged"></asp:TextBox>
<asp:Button ID="Submit" runat="server" Text="Submit" />
</div>
.CS
protected void Titletxt_TextChanged(object sender, EventArgs e)
{
NewsTitlePreview.InnerText = Titletxt.Text;
}
protected void Contenttxt_TextChanged(object sender, EventArgs e)
{
NewsContentPreview.InnerText = Contenttxt.Text;
}
I Tried Adding Autopostback = true... but it only works and refreshes the page and i need to press tab or enter or leave the textbox :(
UPDATE: I Tried This - enter link description here But Still Doesnt Work :(
Just add this script function in your code and in body write onload and call that function.
Javascript:
<script type="text/javascript">
function startProgram() {
setTimeout('errorcheck()', 2000);
}
function errorcheck() {
setTimeout('errorcheck()', 2000);
document.getElementById("NewsTitlePreview").innerText = document.getElementById("Titletxt").value
document.getElementById("NewsContentPreview").innerText = document.getElementById("Contenttxt").value
}
</script>
<body onload="startProgram();">
<form id="form1" runat="server">
<div class="Width960px MarginLeftAuto MarginRightAuto MarginTop10px">
<div class="Padding10px">
<h1 class="Margin0px">Preview</h1>
<hr />
<p></p>
<h3 id="NewsTitlePreview" class="TextAlignCenter" runat="server">Title</h3>
<h5 id="NewsContentPreview" class="TextIndent50px TextAlignJustify" runat="server">Content</h5>
</div>
</div>
<div class="Width960px MarginLeftAuto MarginRightAuto MarginTop10px">
Title
<asp:TextBox ID="Titletxt" runat="server" ></asp:TextBox>
Content
<asp:TextBox ID="Contenttxt" runat="server"></asp:TextBox>
<asp:Button ID="Submit" runat="server" Text="Submit" />
</div>
</form>
</body>
You are right in your analysis of the behavior of the control (it only fires the event when you leave the control), even when you have AutoPostBack="True".
MSDN says it all:
The TextBox Web server control does not raise an event each time the user enters a keystroke, only when the user leaves the control. You can have the TextBox control raise client-side events that you handle in client script, which can be useful for responding to individual keystrokes.
So you either have to be satisfied with the current behavior, or set up some client side event handling to do some validation, etc. client side.
Download and include JQuery library. And also modify title and content textbox so they don't change their Id's
Title
<asp:TextBox ID="Titletxt" ClientIDMode="Static" runat="server"></asp:TextBox>
Content
<asp:TextBox ID="Contenttxt" ClientIDMode="Static" runat="server"></asp:TextBox>
Then add this script and it will work.
<script>
$(document).ready(function () {
$('#Titletxt').on('input', function () {
$("#NewsTitlePreview").text($(this).val());
});
$("#Contenttxt").on('input',function () {
$("#NewsContentPreview").text($(this).val());
});
});
</script>
One of the best idea...
Just change your code to this. it works
ASPX
<asp:ScriptManager ID="ScriptManager1" runat="server">
</asp:ScriptManager>
<asp:UpdatePanel ID="UpdatePanel1" runat="server" UpdateMode="Conditional" ViewStateMode="Enabled">
<ContentTemplate>
<div class="Width960px MarginLeftAuto MarginRightAuto MarginTop10px">
<div class="Padding10px">
<h1 class="Margin0px">Preview</h1>
<hr />
<p></p>
<h3 id="NewsTitlePreview" class="TextAlignCenter" runat="server">Title</h3>
<h5 id="NewsContentPreview" class="TextIndent50px TextAlignJustify" runat="server">Content</h5>
</div>
</div>
<div class="Width960px MarginLeftAuto MarginRightAuto MarginTop10px">
Title
<asp:TextBox ID="Titletxt" runat="server" OnTextChanged="Titletxt_TextChanged"></asp:TextBox>
Content
<asp:TextBox ID="Contenttxt" runat="server" onchange="Contenttxt_TextChanged"></asp:TextBox>
<asp:Button ID="Submit" runat="server" Text="Submit" />
</div>
</ContentTemplate>
</asp:UpdatePanel>
.CS
protected void Titletxt_TextChanged(object sender, EventArgs e)
{
NewsTitlePreview.InnerText = Titletxt.Text;
UpdatePanel1.Update();
}
protected void Contenttxt_TextChanged(object sender, EventArgs e)
{
NewsContentPreview.InnerText = Contenttxt.Text;
UpdatePanel1.Update();
}
Try this it will work this how change event call using jquery dont forget to add google apis
<script>
$('#txtbox').change(function() {
alert("change Event");
});
</script>

accessing checkbox inside listview?

i have a group of listviews with a checkbox in each listview as:
<telerik:RadListView Skin="Vista" ID="RadListView3" DataSourceID="SqlDataSource_subentry"
runat="server" ItemPlaceholderID="EmployeesContainer" DataKeyNames="ID">
<LayoutTemplate>
<fieldset id="FieldSet1">
<legend>Issues</legend>
<asp:PlaceHolder ID="EmployeesContainer" runat="server" ></asp:PlaceHolder>
<br />
<br />
</fieldset>
</LayoutTemplate>
<ItemTemplate>
<div style="width:200px; height:165px; -webkit-border-radius: 20px;-moz-border-radius: 20px; border-radius: 20px;
border:2px solid black; background-color:#00FFFF; text-align:center; margin-top:20px; margin-bottom:10px;
margin-left:20px; ">
<br />
<div style=" width:190px; height:auto; font-size:small;color:#000099; text-align:left; margin-left:12px;"><%#Eval("Worked_Project")%>
<label id="Label1" runat="server"><%# Eval( "ID" ) %></label>
<asp:CheckBox ID="MyCheckBox" runat="server" Text=<%# Eval( "ID" ) %>/></div>
<div style="width:190px; height:auto; font-size:small;color:black;text-align:center; padding-left:2px; margin-left:5px;" ><%# DataBinder.Eval(Container.DataItem, "Week_Ending", "{0:d/M/yyyy }")%></div>
<div style=" width:190px; height:75px; font-size:large; color:#000099; text-align:center; "><%#Eval("Activity")%> </div>
<div style=" width:190px; height:auto; font-size:small;color:black; text-align:left; margin-left:12px; margin-bottom:5px; "><%#Eval("UserId")%> </div>
</div>
</ItemTemplate>
on a button click i want to pick the id assocaiated with a particular checkbox as:
protected void Button1_Click(object sender, EventArgs e)
{
foreach (Control ctl in RadListView3.Controls)
{
CheckBox chk = (CheckBox)ctl.FindControl("MyCheckBox");
if (chk.Checked== true)
{
string value = chk.Text.ToString();
Session["id"] = value.ToString();
Label2.Text = Session["id"].ToString();
}
}
}
but it is giving error on line of code:
if (chk.Checked== true)
and the error is
Object reference not set to an instance of an object.
plzz help me out
Try this:
protected void RadListView1_ItemCommand(object sender,Telerik.Web.UI.RadListViewCommandEventArgs e)
{
CheckBox button = (CheckBox)e.ListViewItem.FindControl("CheckBox1");
if (e.CommandName == "Approve")
{
if (button.Checked == true)
{
//your code
}
else
{
//your code
}
}
}
or if you need to pick id on Button click only (loop) follow below link.
http://www.telerik.com/community/forums/aspnet-ajax/listview/get-selected-value-of-radlistview.aspx
You have to check type of this control first
CheckBox chk = ctl as CheckBox ;
if (chk !=null)
{
//do something
}
more info. about as
keyword

UpdatePanel, ModalPopupExtender, and enter keypress issues

Have an UpdatePanel that contains 2 panels with default buttons set to listen to enter key presses. That UpdatePanel is the PopupControl for a ModalPopupExtender.
Running into an issue when pressing enter in the modal popup in which the entire page posts back. Any ideas? Here are some code snippets (I've removed the extraneous fields...):
<div runat="server" id="divShippingEstimatorPopup" class="shippingEstimatorModalPopup">
<asp:UpdatePanel ID="upPopup" runat="server">
<ContentTemplate>
<asp:Panel runat="server" ID="pnlShippingEstimator" DefaultButton="lnkbtnGetEstimates">
<div class="title content_title">Shipping Estimator</div>
<asp:Label runat="server" ID="lblMessage" />
<table cellpadding="0" cellpadding="0" class="shipping">
<!-- Removed to shorten code snippet -->
<tr>
<td colspan="2">
<div class="buttonHolder">
<Monarch:LinkButtonDefault runat="server" ID="lnkbtnGetEstimates" CssClass="button_action button_margin_right" CausesValidation="false">Get Estimates</Monarch:LinkButtonDefault>
<asp:LinkButton runat="server" ID="lnkbtnCancel" CssClass="button_secondary button_secondary_fixed" CausesValidation="false">Cancel</asp:LinkButton>
<div class="clear"></div>
</div>
<div class="clear"></div>
</td>
</tr>
</table>
</asp:Panel>
<asp:Panel runat="server" ID="pnlShippingOptions" DefaultButton="lnkbtnSetEstimate">
<div class="shippingOptionsHolder" runat="server" id="divShippingOptionsHolder">
<!-- Removed to shorten code snippet -->
<div class="buttonHolder">
<Monarch:LinkButtonDefault runat="server" ID="lnkbtnSetEstimate" CssClass="button_action">Set Estimate</Monarch:LinkButtonDefault>
<div class="clear"></div>
</div>
<div class="clear"></div>
</div>
</asp:Panel>
</ContentTemplate>
</asp:UpdatePanel>
Keep in mind the LinkButtonDefault is just this:
public class LinkButtonDefault : LinkButton
{
private const string AddClickScript = "SparkPlugs.FixLinkButton('{0}');";
protected override void OnLoad(EventArgs e)
{
string script = String.Format(AddClickScript, ClientID);
Page.ClientScript.RegisterStartupScript(GetType(), "click_" + ClientID,
script, true);
base.OnLoad(e);
}
}
Finally, here is the rest of the control:
<asp:UpdatePanel runat="server" ID="upGetEstimate">
<ContentTemplate>
<asp:LinkButton runat="server" ID="lnkbtnGetEstimate" CausesValidation="false">Get Estimate</asp:LinkButton>
</ContentTemplate>
</asp:UpdatePanel>
<ajaxToolKit:ModalPopupExtender ID="shippingEstimatorPopupExtender" runat="server" TargetControlID="lnkbtnFake" PopupControlID="divShippingEstimatorPopup" BackgroundCssClass="monarchModalBackground"></ajaxToolKit:ModalPopupExtender>
<asp:LinkButton runat="server" ID="lnkbtnFake" style="display:none;"/>
<Monarch:PopupProgress ID="popupProgressGetEstimate" runat="server" AssociatedUpdatePanelId="upGetEstimate" />
<Monarch:PopupProgress ID="popupProgressGetEstimates" runat="server" AssociatedUpdatePanelId="upPopup" />
Basically, the user clicks Get Estimate, a progress bar appears while it loads the form, the form shows in a modal popup. I'm guessing this is something simple, but I can't just get the right combination to get this working properly.
First of all try what happens if you use your scriptmanager to register script in the code behind.
I use this method for registering scripts:
public static void RegisterStartupScript(Control c, string script)
{
if ((ToolkitScriptManager.GetCurrent(c.Page) as ToolkitScriptManager).IsInAsyncPostBack)
ToolkitScriptManager.RegisterStartupScript(c, c.GetType(), "Script_" + c.ClientID.ToString(), script, true);
else
c.Page.ClientScript.RegisterStartupScript(c.GetType(), c.ClientID, script, true);
}
This checks if you have ScriptManager in your page. If it doesn't, it uses the full postback version.

Categories

Resources