DropdownList Linked to a Textbox - c#

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.

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.

Invalid postback or callback argument. AutoPostBack is set and also !Page.IsPostBack in Page_Load

Im getting the following error when I click on any item in my ListBox:
Invalid postback or callback argument. Event validation is enabled
using in configuration or <%#
Page EnableEventValidation="true" %> in a page. For security
purposes, this feature verifies that arguments to postback or callback
events originate from the server control that originally rendered
them. If the data is valid and expected, use the
ClientScriptManager.RegisterForEventValidation method in order to
register the postback or callback data for validation.
However, I've set AutoPostBack="True" in my ListBox and also in my DropDownList:
<%# Page Language="C#" EnableEventValidation="false" AutoEventWireup="true" CodeBehind="Form1.aspx.cs" Inherits="WebApplication1.Form1" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:DropDownList ID="dropDown" runat="server" AutoPostBack="True" Height="19px" Width="226px">
</asp:DropDownList>
</div>
<asp:ListBox ID="ListBox1" runat="server" AutoPostBack="True" Height="349px" Width="501px" OnSelectedIndexChanged="ListBox1_SelectedIndexChanged" ></asp:ListBox>
<br />
</form>
</body>
</html>
and I've set if (!Page.IsPostBack) in my .cs code:
using System;
using System.Collections.Generic;
using System.Web.UI;
namespace WebApplication1
{
public partial class Form1 : System.Web.UI.Page
{
public ServiceReference1.WebService1SoapClient client= new ServiceReference1.WebService1SoapClient();
public localhost.WebService1 asd = new localhost.WebService1();
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
List<string> igralci = new List<string>();
foreach (localhost.Igralec ig in asd.vrniVseIgralce())
{
igralci.Add(ig.id + ", " + ig.ime + ", " + ig.priimek + ", " + ig.letoRojstva + "\n");
}
ListBox1.DataSource = igralci;
ListBox1.DataBind();
List<string> klubi = new List<string>();
klubi.Add("Vsi klubi");
foreach (localhost.Klub ig in asd.vrniVseKlube())
{
klubi.Add(ig.naziv);
}
dropDown.DataSource = klubi;
dropDown.DataBind();
}
}
protected void ListBox1_SelectedIndexChanged(object sender, EventArgs e)
{
string script = "alert(\"Hello!\");";
ScriptManager.RegisterStartupScript(this, GetType(),
"ServerControlScript", script, true);
}
}
}
Anyone know how to get rid of the error?
The error it self says you need to add "<%# Page EnableEventValidation="true" %> " in page, like below :-
" <%# Page Language="C#" AutoEventWireup="false" EnableEventValidation="false" CodeBehind="Form1.aspx.cs" Inherits="WebApplication1.Form1" %>"
and the error gets sorted out.

Looping throu random amount of textboxes and get values

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

ListBox SelectedIndex always -1 in slectedindexchanged event handler

In the sample code there are two listboxes. In ListBox1 the items are defined in Default.aspx. In ListBox2 they are defined in the codefile. ListBox1 behaves as expected, the text box is updated whenever an item is selected. When ListBox2 triggers an event the selectedindex is always -1.
Default.aspx:
<%# Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:ListBox ID="ListBox1" runat="server" OnSelectedIndexChanged="lb1_OnSelectedIndexChanged" AutoPostBack="true">
<asp:ListItem>a</asp:ListItem>
<asp:ListItem>b</asp:ListItem>
</asp:ListBox>
<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
<asp:ListBox ID="ListBox2" runat="server" OnSelectedIndexChanged="lb1_OnSelectedIndexChanged" AutoPostBack="true">
</asp:ListBox>
<asp:TextBox ID="TextBox2" runat="server"></asp:TextBox>
</div>
</form>
</body>
</html>
Default.aspx.cs:
using System.Collections.Generic;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
List<string> ab = new List<string>();
ab.Add("a");
ab.Add("b");
ListBox2.DataSource = ab;
ListBox2.DataBind();
ListBox1.SelectedIndexChanged += new EventHandler(lb1_OnSelectedIndexChanged);
ListBox2.SelectedIndexChanged += new EventHandler(lb2_OnSelectedIndexChanged);
}
protected void lb1_OnSelectedIndexChanged(object sender, EventArgs e)
{
if (ListBox1.SelectedIndex != -1)
{
TextBox1.Text = ListBox1.SelectedItem.Text;
}
}
protected void lb2_OnSelectedIndexChanged(object sender, EventArgs e)
{
if (ListBox2.SelectedIndex != -1)
{
TextBox2.Text = ListBox2.SelectedItem.Text;
}
}
}
The list of items has been moved to Default.aspx to get it working, but I'd really like to know what I'm doing wrong with this. -- Thanks!
You can't databind ListBox2 on every page load. Try:
Page_Load()...
{
if(!IsPostBack)
{
//databind listbox2
}
}
Try reading up a bit on the ASP.NET page lifecycle. On the postback, the ListBox2 will have it's correct state due to viewstate.
Your current code resets it. Hence the -1.

Getting a string in code-behind containing the selections in a multi-select listbox?

What I want to do is take all of the selected items from a milti-select listbox and put them in a comma separated string, so I can store it in a table. I've searched and found code, but for some reason the qualifier is never found to be "true". It sees every selected item as "false". Am I processing this in the wrong order?
Here's my ASP section (cut because it's a HUGE file, but this is the important stuff):
<%# Page Language="C#" MasterPageFile="~/Site.Master" AutoEventWireup="true" CodeBehind="WebForm1.aspx.cs" Inherits="PBR.WebForm1" MaintainScrollPositionOnPostback="true"%>
<%# Register Assembly="AjaxControlToolkit" Namespace="AjaxControlToolkit" TagPrefix="AJAXControls" %>
<asp:Content ID="Content1" ContentPlaceHolderID="HeadContent" runat="server">
<link rel="stylesheet" href="Styles/ui.all.css" type="text/css" media="screen" />
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="MainContent" runat="server" >
<asp:ScriptManager ID="ScriptManager2" runat="server">
</asp:ScriptManager>
<div>
<asp:UpdatePanel ID="UpdatePanelX" runat="server" UpdateMode="Conditional" Height="390px"
Width="900px" BorderStyle="Groove" BorderWidth="2px">
<ContentTemplate>
<AJAXControls:TabContainer runat="server" ID="tabContainer" Height="373" Width="900" >
<AJAXControls:TabPanel ID="secondTab" HeaderText="Tracking Page 2" runat="server">
<ContentTemplate>
<div style="border:1px solid blue;">
<asp:Panel ID="Panel2" runat="server" Height="40px" style="margin-left: 19px"
Width="860px">
<table>
<tr>
<td width="170">System/Document Change:</td>
<td width="30"><asp:ListBox id="ddlSysDocChg" runat="server" Width="90px" Rows="2" SelectionMode="Multiple"></asp:ListBox></td>
<td width="40"></td>
<td width="200">System/Document Change Completed:</td>
<td width="20"><asp:CheckBox ID="chkSysDocChg" runat="server" Text=" " AutoPostBack="true" /></td>
</tr>
</table>
</asp:Panel>
</div>
<p></p>
<div>
</div>
</ContentTemplate>
</AJAXControls:TabPanel>
</AJAXControls:TabContainer>
</ContentTemplate>
</asp:UpdatePanel>
<br />
<asp:Button ID="btnSubmit" Text="Submit" OnClick="btnSubmit_OnClick"
runat="server" />
</div>
</asp:Content>
In my code-behind, I have this (as you can see, I've tried it 2 different ways and I believe I found both methods on this very website):
protected void btnSubmit_OnClick(object sender, EventArgs e)
{
// Read the selected items from the listbox
//string SQLCode = "";
var selectedQuery = ddlSysDocChg.Items.Cast<ListItem>().Where(item => item.Selected);
string SQLCode = String.Join(",", selectedQuery).TrimEnd();
//foreach (ListItem listitem in ddlSysDocChg.Items)
// {
// if (listitem.Selected == true)
// {
// SQLCode = SQLCode + ", " + listitem;
// }
// }
}
Can anyone tell me why it always tells me there's nothing selected?
EDIT:
This is what's in my Page_Load:
protected void Page_Load(object sender, EventArgs e)
{
using (SqlConnection con = new SqlConnection(str))
// Check to see which tabs should be active
LoadTabPages();
{
try
{
string strSQL = "SELECT ComboValue, ComboText FROM dbo.tblComboBoxes WHERE ComboName = 'ddlSysDocChg' ORDER BY ComboText ASC;";
SqlDataAdapter adapter = new SqlDataAdapter(strSQL, str);
DataSet DailyRun = new DataSet();
adapter.Fill(DailyRun);
ddlSysDocChg.DataSource = DailyRun;
ddlSysDocChg.DataTextField = "ComboText";
ddlSysDocChg.DataValueField = "ComboValue";
ddlSysDocChg.DataBind();
foreach (ListItem item in ddlSysDocChg.Items)
{
item.Attributes.Add("Title", item.Text);
}
// Insert a blank row into the DropDownLists so there is no default name
ddlSysDocChg.Items.Insert(0, new ListItem("", ""));
}
catch (Exception ex)
{
// Handle the error
Console.WriteLine("Making Call to " + ex + "");
}
}
}
I think it's because your list is in an updatepanel whose postback is 'Conditional', and the button is 'outside' the updatepanel.
Try putting it 'inside' the update panel as in this tutorial:
http://msdn.microsoft.com/en-us/library/Bb399001(v=VS.100).aspx
Or alternatively, specify the button as a 'Trigger' as in the same tutorial.
Do you databind the ListBox also postbacks? Check the IsPostBack property:
protected void Page_Load(Object sender, EventArgs e)
{
if(!IsPostBack) DataBindListBox();
}

Categories

Resources