Looping throu random amount of textboxes and get values - c#

In classic ASP i could do this when looping throu a unknown inputfields:
<input id="textbox1" type="text">
<input id="textbox2" type="text">
<input id="textbox3" type="text">
<input id="textbox4" type="text">
<input id="textbox5" type="text">
For i = 1 To 5
strTextbox = request.form("textbox" & i)
If strTextbox <> "" Then
// Do the magic!
End If
Next
With this the user could input values to textbox 1, 3, 4 and 5 or maybe only 1 and 2 and i could collect the values inputs in the For loop.
How could i do this in C#?
I cant do this because it dosent like that i add a i in the middle om my textbox.Text;
for (int i = 1; i < 6; i++)
{
strTextbox = textbox[i].Text;
if (!string.IsNullOrEmpty(strTextbox)
{
// Do the magic!
}
}
I now have a lot of if:s checking every textbox inside the loop but it got to be a easyer way?

You can use FindControl on the NamingContainer of your textboxes.
If they're are on top of the page and not nested in other controls like GridView:
for (int i = 1; i < 6; i++)
{
string strTextbox = "textbox" + i.ToString();
TextBox txt = this.FindControl(strTextbox) as TextBox;
if (txt != null && !string.IsNullOrEmpty(txt.Text))
{
// ...
}
}
But i would use more meaningful names instead.
I want access to the textboxes from a button_click event only on the
actual page. The controls are inside a panel.
Then i would use this LINQ approach:
List<TextBox> filledArticleTBS = txtPanel.Controls.OfType<TextBox>()
.Where(txt => txt.ID.StartsWith("textbox") && !String.IsNullOrEmpty(txt.Text))
.ToList();

I did manage to get this working with some extra lines.
So the final code was to first find Contentplaceholder in my top master, then search for the Contentplaceholder in my nested Masterpage and finaly search for the textbox. It works, but when debugging i can see that there are some other isues with the code where in some cases the textbox is'nt found. I'm going back to my previusly working code where i access all the controls directly and not with findcontrol. But if someone is intrested this worked (almost) for me:
My Top Masterpage (Site.Master)
<%# Master Language="C#" AutoEventWireup="true" CodeBehind="Site.master.cs" Inherits="mysite.SiteMaster" %>
<html>
<head>
// MasterPage head stuff
// ...
</head>
<body>
<asp:ContentPlaceHolder ID="MainContent" runat="server">
// My contentpages that use only the top masterpage
// My contentpage contacts.aspx begin here, This is in a separate file called contacts.aspx.
// In code the contentpage is theoretically here, when the site runns it works in another way. Here things are explained; http://odetocode.com/articles/450.aspx
<%# Page Title="" Language="C#" MasterPageFile="~/Site.Master" AutoEventWireup="true" CodeBehind="contacts.aspx.cs" Inherits="mysite.contacts" %>
<asp:Content ID="contactsContent" ContentPlaceHolderID="MainContent" runat="server">
// Here is the content of a contentpage (contacts.aspx) that use the Site.Master
</asp:Content>
// contentpage contacts.aspx end here
</asp:ContentPlaceHolder>
</body>
</html>
My Nested Masterpage (XYZ.master)
<%# Master Language="C#" MasterPageFile="~/Site.Master" AutoEventWireup="true" CodeBehind="XYZMasterPage.master.cs" Inherits="mysite.XYZ.XYZMasterPage" %>
<asp:Content ID="NestedMasterPageContentPlaceHolder" ContentPlaceHolderID="MainContent" runat="server">
Nested MasterPage stuff
...
<asp:ContentPlaceHolder ID="NestedMainContent" runat="server">
// Here is my contentpage where textbox1, 2, 3 etc. is
// Here is the content of a contentpage (batch.aspx) that use the nested masterpage XYZMasterPage.master
<%# Page Title="" Language="C#" MasterPageFile="~/XYZMasterPage.master" AutoEventWireup="true" CodeBehind="batch.aspx.cs" Inherits="mysite.XYZ.batch" %>
<asp:Content ID="batchInvContent" ContentPlaceHolderID="NestedMainContent" runat="server">
// Here is the content of a contentpage (batch.aspx)
<asp:Panel ID="PanelBatch" Runat="Server" >
<asp:TextBox runat="server" ID="ArticleNr1" />
<asp:TextBox runat="server" ID="ArticleNr2" />
<asp:TextBox runat="server" ID="ArticleNr3" />
<asp:TextBox runat="server" ID="ArticleNr4" />
<asp:TextBox runat="server" ID="ArticleNr5" />
<asp:Button runat="server" ID="buttSubmit" OnClick="buttSubmit_Click" />
</asp:Panel>
</asp:Content>
// contentpage batch.aspx end here
</asp:ContentPlaceHolder>
My codebehindfile for batch.aspx
protected void buttSubmit_Click(object sender, EventArgs e)
{
ContentPlaceHolder parentCP = this.Master.Master.FindControl("MainContent") as ContentPlaceHolder;
ContentPlaceHolder childCP = parentCP.FindControl("NestedMainContent") as ContentPlaceHolder;
string strTextbox = string.Empty;
for (int i = 1; i < 6; i++)
{
strTextbox = "ArticleNr" + i.ToString();
TextBox txt = childCP.FindControl(strTextbox) as TextBox;
if (txt != null && !string.IsNullOrEmpty(txt.Text))
{
// ...
// Insert to db
// ...
}
}
}

Related

Get Master Page Control Value In Content Page static webmethod in c#

I can fetch MasterPage control value in Content Page
but I can't understand how to fetch MasterPage control value in Content Page in static webmethod
on google, I found many interesting articles but all of them use ajax and jquery technology
but ajax and jquery is not suitable for me in this case
any suggestions, please?
my code below
masterpage
public partial class MasterPage : MasterPage
{
public string UserNamePropertyOnMasterPage
{
get
{
// Get value of control on master page
return lblUserName.Text;
}
set
{
// Set new value for control on master page
lblUserName.Text = value;
}
}
}
<form id="form1" runat="server">
<div>
<asp:ContentPlaceHolder ID="ContentPlaceHolder1" runat="server">
</asp:ContentPlaceHolder>
<span style="font-size: 25px; background-color: greenyellow">
<asp:Label ID="lblUserName" runat="server" Text="Shazam"></asp:Label>
</span>
</form>
code-behind of Default.aspx.cs
public partial class _Default : Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
lblCurrentUserName.Font.Size = 20;
lblCurrentUserName.BackColor = Color.Yellow;
lblCurrentUserName.Text = "Value Received in Content Page : " + Master.UserNamePropertyOnMasterPage;
}
}
[WebMethod(EnableSession = true)]
[ScriptMethod]
public static void SetLabel(string UserNamePropertyOnMasterPage)
{
HttpContext.Current.Response.Cache.SetExpires(DateTime.UtcNow.AddMinutes(-1));
HttpContext.Current.Response.Cache.SetCacheability(HttpCacheability.NoCache);
HttpContext.Current.Response.Cache.SetNoStore();
Label Hname = (Label)Master.UserNamePropertyOnMasterPage;
lblCurrentUserName.Text = Hname;
}
}
markup of Default.aspx
<%# Page Title="" Language="C#" MasterPageFile="MasterPage.master"
AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>
<%# MasterType VirtualPath="MasterPage.master" %>
<asp:Content ID="Content1" ContentPlaceHolderID="head" runat="Server">
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="ContentPlaceHolder1" runat="Server">
<asp:Label ID="lblCurrentUserName" runat="server" Text=""></asp:Label>
</asp:Content>
It is not possible to call a master page method from a static web method. This is a fundamental concept to understand in C#. Basically the master page does not exist during the web request. Only the web method is called.
Use JavaScript/jQuery to update the current page HTML.

DropdownList Linked to a Textbox

I am trying to display the selectedIndex of my dropdownlist in the textBox (field number 2) and in my ajax htmlEditor (field number 3). I already can show field number 1 on my dropdown, but I cant seem to show anything on the other boxes, all I get are errors :(, implying that the dataSource has not any items which is weird. Here are my classes.
Messages.aspx
<%# Page Title="" Language="C#" MasterPageFile="~/Site.Master" AutoEventWireup="true" CodeBehind="Messages.aspx.cs" Inherits="ASF.HC.JobApplication.Admin.Messages" %>
<%# Register assembly="AjaxControlToolkit" namespace="AjaxControlToolkit" tagprefix="ajaxToolkit" %>
<asp:Content ID="Content1" ContentPlaceHolderID="HeadContent" runat="server">
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="MainContent" runat="server">
<h2>Messages</h2>
<asp:ScriptManager ID="ScriptManager2" runat="server"></asp:ScriptManager>
<legend>Pick the template to use:</legend>
<asp:dropdownlist id ="ddlTemplate" runat ="server" Height="38px" Width="397px">
<asp:listitem value ="1"> Juan Valdez </asp:listitem >
<asp:listitem Value ="2"> Querido bebe</asp:listitem>
</asp:dropdownlist >
<p> </p>
<asp:TextBox ID="textDos" AutoPostBack="true" runat="server" MaxLength="40"></asp:TextBox>
<ajaxToolkit:HtmlEditorExtender ID="textoTemplate" runat="server" TargetControlID="txtDetails"
EnableSanitization="false" DisplaySourceTab="true" >
</ajaxToolkit:HtmlEditorExtender>
</asp:Content>
Message.aspx.cs
public partial class Messages : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
loadList();
}
public void loadList()
{
try
{
BO.Messages template = new BO.Messages();
ddlTemplate.DataSource = template.GetAll();
ddlTemplate.DataValueField = "Title";
DataSet ds = new DataSet("Templates");
ddlTemplate.DataSource = ds;
ddlTemplate.DataBind();
ddlTemplate.SelectedIndexChanged += DdlTemplate_SelectedIndexChanged;
textDos.Text = ds.Tables[0].Rows[0]["id"].ToString();
} catch (Exception e)
{
}
}
private void DdlTemplate_SelectedIndexChanged(object sender, EventArgs e)
{
//when we change the dropdownlist we need to get the student id and set it to the textbox
DropDownList mydropdownlist = sender as DropDownList;
textDos.Text = mydropdownlist.SelectedValue;
}
}
Been checking this error all day long, with no plausible answer and can not detect what am I doing wrong.
Thanks for your assistance.

ASP how to find controls of type on a child page of a master page

I have a master page master.page.
And I have a child page default.aspx that inheirts master.
How do I preform the following and actually find controls. In the below code I never find my panels.
codebehind - content-page
foreach (Panel pnl in this.Page.Controls.OfType<Panel>())
{
if (pnl.ID.ToUpper() == texthi.ToUpper().Replace(" ", ""))
{
pnl.Visible = true;
}
else
{
pnl.Visible = false;
}
}
aspx - content-page
<%# Page Title="" Language="C#" MasterPageFile="~/secure/Wizard.master" AutoEventWireup="true"
CodeFile="AddWarranty.aspx.cs" Inherits="secure_Warranties_AddWarranty" %>
<asp:Content ID="Content1" ContentPlaceHolderID="ContentPlaceHolder_NavigationPanel"
runat="Server">
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="ContentPlaceHolder1" runat="Server">
<asp:ScriptManager runat="server" ID="sm1">
</asp:ScriptManager>
<div id="header">
<p id="layoutdims">
</p>
</div>
<div class="colmask leftmenu">
<div class="colleft">
<div class="col1">
<asp:Panel runat="server" ID="VehicleInformation" Visible="true">
<legend>VEHICLE INFORMATION</legend>
</asp:Panel>
<asp:Panel runat="server" ID="CustomerInformation" Visible="false">
<legend>CUSTOMER INFORMATION</legend>
</asp:Panel>
</div>
The reason is that Enumerable.TypeOf does not look recursivelsy into child controls but only the top-container. Since you're using it on the page's ControlCollection you'll find only panels which are sitting on the top of the page. But your panels are inside of other divs.
Make the parent div(with class="col1") runat=server(or use Panel) and access it in codebehind:
foreach (Panel pnl in div.Controls.OfType<Panel>())
{
// ...
}

Adding textbox to UserControl in asp.net

I have a simple web page which has a UserControl(.ascx). Here is my UserControl source
<%# Control Language="C#" AutoEventWireup="true" CodeBehind="ucReportTextBox.ascx.cs"
Inherits="Intranet.UserControl.ucReport" %>
<table width="100%">
<tr>
<td>
<asp:TextBox ID="txtQuery" runat="server" Width="250px" />
</td>
</tr>
</table>
And my web page source
<%# Page Title="" Language="C#" MasterPageFile="~/MasterPage/DefaultMasterPage.Master"
AutoEventWireup="true" CodeBehind="ComposeReport.aspx.cs" Inherits="Intranet.MasterPage.WebForm4" %>
<%# Register Src="~/UserControl/UcReportTextBox.ascx" TagName="UcReportTextBox" TagPrefix="uc1" %>
<asp:Content ID="Content1" ContentPlaceHolderID="contentHead" runat="server"/>
<asp:Content ID="Content2" ContentPlaceHolderID="contentBody" runat="server">
<table>
<tr>
<td>
<uc1:UcReportTextBox ID="ucReporttxt" runat="server" />
</td>
</tr>
//includes so many tags
</table>
</asp:Content>
In code behind of my web page
protected void Page_Load(object sender, EventArgs e)
{
InitComponent();
}
private void InitComponent()
{
XDocument document = XDocument.Load("ReportXML.xml");
var parameterTypes = document.Descendants("Type");
foreach (var parType in parameterTypes)
{
if (parType.Value == "string") //TODO Enumerate it !!
{
ucReporttxt.addTextBox();
}
}
}
In code behind of usercontrol
public void addTextBox()
{
TextBox txtBox = new TextBox();
txtBox.ID = "txtBox";
txtBox.Width = 170;
Page.Form.Controls.Add(txtBox);
}
As you understand I'm newer to asp.net , in PageLoad I'm reading XMLfile to whether or not add textbox to page. The codes add textboxes correctly but the textboxes are added at the end of the page. I want to add textbox at the part of ucReportText not the end of the page how can fix it ?
Thanks for your help.
You can add an asp panel to the user control and add the textbox to the panel controls and not the page controls. Then just place the panel where ever you want the textboxes to appear.
<%# Page Title="" Language="C#" MasterPageFile="~/MasterPage/DefaultMasterPage.Master"
AutoEventWireup="true" CodeBehind="ComposeReport.aspx.cs" Inherits="Intranet.MasterPage.WebForm4" %>
<%# Register Src="~/UserControl/UcReportTextBox.ascx" TagName="UcReportTextBox" TagPrefix="uc1" %>
<asp:Content ID="Content1" ContentPlaceHolderID="contentHead" runat="server"/>
<asp:Content ID="Content2" ContentPlaceHolderID="contentBody" runat="server">
<table>
<tr>
<td>
<uc1:UcReportTextBox ID="ucReporttxt" runat="server" />
<asp:panel runat="server" id="pnlContainer"></asp:panel>
</td>
</tr>
//includes so many tags
</table>
</asp:Content>
public void addTextBox()
{
TextBox txtBox = new TextBox();
txtBox.ID = "txtBox";
txtBox.Width = 170;
pnlContainer.Controls.Add(txtBox);
}
In order to control where you dynamically add elements from your code-behind, add a PlaceHolder control to the page and append them there. Something like this:
<%# Control Language="C#" AutoEventWireup="true" CodeBehind="ucReportTextBox.ascx.cs" Inherits="Intranet.UserControl.ucReport" %>
<table width="100%">
<tr>
<td>
<asp:TextBox ID="txtQuery" runat="server" Width="250px" />
<asp:PlaceHolder runat="server" ID="phAdditionalTextBoxes" />
</td>
</tr>
</table>
(Note: It's not entirely clear where you want your dynamic text boxes added, so move the PlaceHolder accordingly.)
And in the code:
TextBox txtBox = new TextBox();
txtBox.ID = "txtBox";
txtBox.Width = 170;
phAdditionalTextBoxes.Controls.Add(txtBox);
The textboxes are being added to the end of the page because that's where Page.Form.Controls.Add(txtBox); puts them, yiou are adding textboxes to the end of the Page holding your UC,
Add a Placeholder control to your UC, then add the new textboxes to the placeholder.

ASP/C#, adding text to textbox problem

For some reason, I cannot get text into any textbox or label!
I'm using Master pages and the code is going in the code behind view. I have created the textbox:
<asp:Textbox ID="whatever" runat="Server">
When I want to add some text I simply add the code in the code behind view like:
whatever.Text = "myText";
I get an error that says:
"System.NullReferenceException:Object reference not set to an instance of an object"
hightlighting this line in red: whatever.Text = "myText";
I guess its because it saying it not there but how can it let me reference the textbox?
Apologies if the answer is on the site, I have searched but found nothing. :)
This is my code in Basket.asp - I've changed the textbox to a label, it's called bskItems
<asp:Content ID="Content3" ContentPlaceHolderID="ContentPlaceHolder3" runat="server">
<asp:Label ID="bskItems" runat="server"></asp:Label>
<div id="cart">
<asp:Button ID="btnCheckout" CssClass="BasketBtnAdd" runat="server" CommandName="checkout" Text="Checkout" />
</div>
</asp:Content>
This is my masterpage, where I'm using a loginView. ContentPlaceHolder3 is where the textbox should be. I only want it to display a count of items.
<asp:LoginView ID="loginView" runat="server">
<LoggedInTemplate>
<asp:LoginName ID="loginName" runat="server" FormatString="Hi, {0}!"/>
(<asp:LoginStatus ID="loginStatus" runat="server" />)
<%
if (HttpContext.Current.User.IsInRole("Admin"))
{
%>
<asp:SiteMapDataSource ID="admin" SiteMapProvider="admin" runat="server" ShowStartingNode="false" />
<asp:Menu ID="Menu" runat="server" DataSourceID="admin">
<StaticItemTemplate>
<%# Eval("Text") %>
</StaticItemTemplate>
</asp:Menu>
<%
}
if (HttpContext.Current.User.IsInRole("Users"))
{
%>
<asp:SiteMapDataSource ID="user" runat="server" SiteMapProvider="user" ShowStartingNode="false" />
<asp:Menu ID="Menu1" runat="server" DataSourceID="user">
<StaticItemTemplate>
<%# Eval("Text") %>
</StaticItemTemplate>
</asp:Menu>
<%
}
%>
<asp:ContentPlaceHolder ID="ContentPlaceHolder2" runat="server"></asp:ContentPlaceHolder>
<asp:ContentPlaceHolder ID="ContentPlaceHolder3" runat="server"></asp:ContentPlaceHolder>
</LoggedInTemplate>
<AnonymousTemplate>
<asp:LoginStatus ID="loginStatus" runat="server" />
<asp:SiteMapDataSource ID="anon" runat="server" SiteMapProvider="anon" ShowStartingNode="false" />
<asp:Menu ID="Menu2" runat="server" DataSourceID="anon">
<StaticItemTemplate>
<%# Eval("Text") %>
</StaticItemTemplate>
</asp:Menu>
</AnonymousTemplate>
</asp:LoginView>
In addition to the other answers, if you're setting the value in Page.OnLoad, remember that the Master page controls haven't been created yet.
Here's a complete layout of the order in which things happen: Complete Lifecycle of an ASP Page
What I usualy do is to make the control visible as a property of my MasterPage.
On the master page (AMasterPage.master):
public TextBox MyTextBox { get { return this.theTextBoxControl; } }
So then, on a child using this masterPage (APage.aspx) :
((AMasterPage)this.Master).MyTextBox.Text = "myText";
When accessing Master Page members from Code-Behind in a Content Place Holder file, I believe you need to do:
this.Master.whatever.Text = "new Text";
Check this link on ASP.NET Master Pages, from MSDN.
You need to do get a reference to the textbox on the master page, then set the text
TextBox tb = Master.Page.FindControl("whatever") as TextBox;
if(tb != null)
{
tb.Text = "myText";
}
Set the ClientIDMode on the textbox to "Static". When the page is rendered it assigns the TextBox's ID to something random. By changing the ClientIDMode to "Static", you should be able to reference the ID because the ID will stay the same and not change.
Or try adding an OnDataBinding event handler and casting the "sender" as a (TextBox). For example:
protected void TextBox_OnDataBinding(object sender, EventArgs e)
{
var txt = (TextBox)sender;
txt.Text = "Something";
}
This should talk to the control directly.

Categories

Resources