How to display remaining textbox characters in a label in C#? - c#

I'm not sure if I have the last bit right? I changed the max length of the textbox to 140. I can't seem to use TextLength. Help please?! I have this so far:
protected void textBox_TextChanged(object sender, EventArgs e)
{
characterCountLabel.Text = textBox.MaxLength - textBox.TextLength;
}

characterCountLabel.Text is in string format. So you might want to convert it before you set its value like this:
protected void textBox_TextChanged(object sender, EventArgs e)
{
characterCountLabel.Text = (textBox.MaxLength - textBox.Text.Length).ToString();
}
I think you are trying to display the remaining characters the user can input to your text box? I suggest that you can set the limit as constant like this:
protected void textBox_TextChanged(object sender, EventArgs e)
{
characterCountLabel.Text = (140 - textBox.Text.Length).ToString(); // in here 140 is your limit
}
If you are using ASP.NET in C#. Don't limit yourself from using javascript like in this link

I think this will be a better answer...
Header code:
<script language="javascript" type="text/javascript">
function getCountDown()
{
//Get the Textbox control
var textField = document.getElementById("<%#TextBox1.ClientID %>");
//Do the math of chars left and pass the value to the label
document.getElementById('<%#Label1.ClientID %>').innerHTML = textField.maxLength - textField.value.length;
return false;
}
</script>
ASP code:
<asp:TextBox ID="TextBox1" runat="server" MaxLength="729" Height="80px"
Width="591px" onkeyup="getCountDown();" ClientIDMode="Static"></asp:TextBox>
<asp:Label ID="Label1" runat="server" Text="" ClientIDMode="Static"></asp:Label>
It is important to set the TextBox and Label control's property as ClientIDMode="Static" otherwise the control name will not be found on the javascript.
CS code:
protected void Page_Load(object sender, EventArgs e)
{
Page.Header.DataBind();
}
That's it for a SingleLine TextBox.
Now for a MultiLine TextBox you need to add this on your Page_Load() so the maxLength takes the TextBox1.MaxLength value.:
this.TextBox1.Attributes.Add("maxLength", TextBox1.MaxLength.ToString());
Also the MaxLength property of the TextBox doesn't work when is on Multiline mode so you need to add on your javascript getCountDown() function the following lines:
// Check if user is entering more than the limit of characters
if (textField.value.length >= textField.maxLength) {
// Cut extra text
document.getElementById("<%#TextBox1.ClientID %>").innerHTML = textField.value.substring(0, textField.maxLength);
}
add them right after the var textField = document.getElementById("<%#TextBox1.ClientID %>"); line. This is to prevent the user from entering more characters than the MaxLength value.
Pablo

Related

How to get the newly entered text in the TextChanged event?

I'm doing a page navigation control. After typing a new number in text box and Enter,
void pageNoTextBox_TextChanged(object sender, EventArgs e)
The above event is called.But I am still getting the old text from the text box in the following statement
newPageNumber = Int32.Parse(pageNoTextBox.Text.Trim());
for example if the textbox had 1 and and I entered 12, what I am getting is 1 in the TextChanged event where as javascript returns new value.
<asp:TextBox ReadOnly="false" CssClass="txtfld_s" ForeColor="white" ID="pageNoTextBox" runat="server" Text="" AutoPostBack="true" CausesValidation="True" OnTextChanged="pageNoTextBox_TextChanged"></asp:TextBox>
This is the text box. Is there any way to get the newly entered text using C#?
Well I think this will do the thing you want.
private void pageNoTextBox_TextChanged(object sender, EventArgs e)
{
TextBox textbox = sender as TextBox;
if(textbox != null)
{
string theText = textbox.Text;
}
}

How to get SelectedValue of DropdownList without postback or updatepanel

I have a DropDownList which i am binding on page load. i dont have any buttons or anything. as soon as user selects the value in dropdown i need to show that value in label. i am not sure why this is not working. please help.
public string SelectedStore { get; set; }
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
BindStoresList();
}
}
protected void BindStoresList()
{ storeDDList.AppendDataBoundItems = true;
storeDDList.Items.Add(new ListItem("Select store", "-1"));
TempCollection stores = TempDataSource.LoadForCriteria("ALL", "Code ASC");
storeDDList.DataSource = stores;
storeDDList.DataTextField = "DisplayName";
storeDDList.DataValueField = "Code";
storeDDList.DataBind();
}
protected void storeDDList_SelectedIndexChanged(object sender, EventArgs e)
{
SelectedStore = storeDDList.SelectedValue.ToString();
selectedItem.Text = SelectedStore;
}
I dont need any kind of jquery stuff as i am going to add gridview which binds depending on the value of dropdown..
****** EDITS *******
if i set AutoPostBack=True then on page refresh my DropDownList doesn't bind at all as you can see in Page_Load Method, it will not call BindStoresList() method.
***** ANSWER *****
For people who might get stuck with this..
i was setting the EnableViewState to True for the DropDownList, so after page refreshes the SelectedValue was getting lost. after removing the EnableviewState and setting AutoPostBack to Ture working fine...
You can Use JavaScript . Set the OnChange attribute for your DropDownList to call a JS function and Change your label text there:
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
BindStoresList();
storeDDList.Attributes["onChange"] = "ChangeLabelText();";
}
}
JS function :
<script type="text/javascript">
function ChangeLabelText() {
var lbl = document.getElementById("<%=lbl.ClientID%>");
var ddl = document.getElementById("<%=ddl.ClientID%>");
lbl.innerHTML = ddl.options[ddl.selectedIndex].text;
}
</script>
You have to set the AutoPostBack=True for the dropdown, it will automatically send the call to server side without need to extra button.
You may do it using Javascript, handle the OnChange event of the DropDownList and set the text of the label you want
<asp:DropDownList ID="ddl" runat="server" onchange="ddl_change(this.value)"/>
<script language="javascript" type="text/javascript">
function ddl_change(value)
{
var lbl = document.getElementById('<%= yourlabel.ClientID %>');
lbl.value = value;
}
</script>
Good luck.

Null Value in Label object

I have created on GridView with Label. I have written store procedure to get StatusCode
SELECT StatusCode
From TableName
This line in GridView
< asp:Label ID="lblStatusCode" runat="server" Visible="false"
Text='<%#DataBinder.Eval(Container.DataItem, "StatusCode")%>' />
These lines in .cs file
Label lblStatusCode = (Label)row.FindControl("lblStatusCode");
objJV.Status = Convert.ToInt32(lblStatusCode.Text);
but in lblStatusCode.Text it is showing NULL even though there is value in Table.
When I execute stored procedure independently it is giving values.
// bind function
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
BindJVJobValidationDetails();
}
}
protected void BindJVJobValidationDetails()
{
JVSummary objJV = new JVSummary();
DataSet dataJobValidation = new DataSet();
if (SessionVariables.PERID != null)
{
dataJobValidation = objJV.GetjvTransaction(SessionVariables.PERID);
gvEmployee.DataSource = dataJobValidation;
gvEmployee.DataBind();
}
}
What might be the problem...?
The text is applied to the control on the page AFTER the code behind runs. Can't you set the text in the code behind?
Edit: You are setting the value of the label on the page i.e aspx / ascx using Container.DataItem but this value is set after the code behind has run. Basically, when the code behind looks at the control it's text property hasn't been set yet. Instead, add a DataRowBinding event to your GridView and set the lblStatusCode.Text in the event in the code behind.
Please try this code on gridview's event
OnRowDataBound="GridView_RowDataBound"
protected void GridView_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
if ((e.Row.DataItem) != null)
{
Label lblStatusCode = (Label)e.row.FindControl("lblStatusCode");
objJV.Status = Convert.ToInt32(lblStatusCode.Text);
}
}
}

Retrieving MasterPage textbox Control on a postback to another page

I have spend two days trying to figure out the solution to this problem, even tried ExpertExchange and still I can't get a solution. I am a very novice programmer to ASP.Net (using C#) and I DON'T want to use a string/url post
I have a MasterPage of which has a textbox called tbSearchString. It is a simple box that a user can enter something and then it does a Postback to another page SearchResults.aspx So I also have other pages, like Default.aspx that uses the MasterPage.
I have tried nearly everything and have read nearly every post I could find on the net and no mater what the Variables are always Null.
I have use this code on the searchResults loadpage event and Every one of these variables are null, even though I enter a value in the page text box and click the button to postback to the SearchResults page, the only time it works is if I am on the searchResults page and submit.
SearchResults back end page
protected void Page_Load(object sender, EventArgs e)
{
TextBox SearchString;
TextBox SearchString2;
TextBox SearchString3;
TextBox SearchString5;
if (Page.PreviousPage != null) //This is true on every test
{
SearchString = (TextBox)Page.PreviousPage.Master.FindControl("tbSearchString");
SearchString2 = (TextBox)PreviousPage.Master.FindControl("tbSearchString");
SearchString3 = (TextBox)Master.FindControl("tbSearchString");
TextBox LoginControlx = (TextBox)PreviousPage.FindControl("Form1");
if (LoginControlx != null)
{
TextBox SearchString4 = (TextBox)LoginControlx.FindControl("tbSearchString");
}
}
MainWebsite.Master page Code
<asp:TextBox ID="tbSearchString" runat="server"></asp:TextBox>
<asp:Button ID="btnSearch1" runat="server" Text="Search" PostBackUrl="~/SearchResultRentalEquiptment.aspx" />
I don't have anything in the CS backend page
So on the Default.aspx page
nothing special Just the Masterpage and some text content, I enter some text in the textbox goes to the SearchResults page and I can not get the darn value from the Textbox control from the Default or any other page.
What say you wise ones?
how do you redirect your form to search result form? if you are using Response.redirect, the value under Page.PreviousPage.Master.FindControl will be null . Try to use Server.Transfer to see if it works.
Here's one way:
Assuming this is your Master Page code:
<asp:TextBox ID="searchbox" runat="server" /><br />
<asp:Button ID="sendSearch" runat="server" PostBackUrl="~/Results.aspx" Text="Search" />
At the end of the day, it's all about HTTP POST, so in the target page Results.aspx PageLoad:
protected void Page_Load(object sender, EventArgs e)
{
string _foo = Request.Form[this.Master.FindControl("searchbox").UniqueID];
}
Hth....
Check out Session. I use it all the time when I need to get data from one page to another. I'm not currently able to write out a full example for you, but off the top of my head the following should work:
//page1.aspx:
protected void btnSubmit_Click(object sender, EventArgs e)
{
string greetingString = "Hello";
Session["MyValue"] = greetingString;
Response.Redirect("page2.aspx");
}
//page2.aspx:
protected void Page_Load(object sender, EventArgs e)
{
Response.Write(Session["MyValue"].ToString()); //prints "Hello"
}

How do I retrieve the ListItem value dynamically

I have the following code:
<asp:BulletedList ID="filingList" runat="server" DisplayMode="LinkButton"
onclick="filingList_Click">
</asp:BulletedList>
<asp:Literal ID="filingLiteral" runat="server"></asp:Literal>
and in the backend I fill the bulleted list with ListItems (where AlternateFileUrl is a url string that points to text formatted in html):
foreach (ShortFiling file in filingArray)
{
filingList.Items.Add(new ListItem(file.Type.ToString() + " "
+ file.Date.ToString(), file.AlternateHtmlFileUrl));
}
How do I access the text of the value of the item that's clicked on in the filingList then set it to the asp:Literal control? Here is the empty event handler that I defined and assume that I need to put the code in to set the asp:literal to the value of the specified ListItem.
protected void filingList_Click(object sender, BulletedListEventArgs e)
{
//put code here to set the asp:Literal text to
//the value of the item that is clicked on
}
protected void filingList_Click(object sender, BulletedListEventArgs e)
{
var value = filingList.Items[e.Index].Value;
filingLiteral.Text = value;
}
UPDATE 2
Ok you want the text from that URL, keep your markup as it was and change the code behind to this:
protected void filingList_Click(object sender, BulletedListEventArgs e)
{
var value = filingList.Items[e.Index].Value;
using(var client = new WebClient())
{
string downloadString = client.DownloadString(value);
filingLiteral.Text = downloadString;
}
}
You will need to add the System.Net namespace.
If I have understood your question correctly, you would just handle the click event of the BulletedList control, like:
protected void filingList_Click(object sender, BulletedListEventArgs e)
{
BulletedList bull = (BulletedList)sender;
ListItem li = bull.Items(e.Index);
filingLiteral.Text = li.Value;
}

Categories