How to get the newly entered text in the TextChanged event? - c#

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;
}
}

Related

gridview and radio button list on browser back button

On my aspx page there is a RadioButtonList and it contains list items named “additions” and “termination”. Also there two gridview “GV_addition” and “GV_termination”. On selecting the radio button “addition”, then the gridview “GV_addition” will be shown. When item “termination” is selected, then the gridview “GV_termination” will be shown.
On radio button changed event, it is working correctly. But my problem is , when I click browser back button, the radio button selection and corresponding grid view not showing correctly. I got issue, “Gv_termination” is showing when radio button “addition” is selected. This issue is showing only when I click browser back button.
Please find my below code
<asp:RadioButtonList ID="RadioButtonList1" runat="server"
onselectedindexchanged="RadioButtonList1_SelectedIndexChanged" AutoPostBack="true">
<asp:ListItem Text="addition" Value="addition"> </asp:ListItem>
<asp:ListItem Text="termination" Value="termination"></asp:ListItem>
protected void RadioButtonList1_SelectedIndexChanged(object sender, EventArgs e)
{
if (RadioButtonList1.SelectedIndex == 0)
{
GV_addition.Visible = true;
GV_termination.Visible = false;
}
else
{
GV_termination.Visible = true;
GV_addition.Visible = false;
}
}
I could not understand why the why the radio button selection and corresponding gridview visiblity is not working on the browsers back button event. Can any one help me to solve this issue?
Please try below steps. For me the same scenario worked.
I could see the values are updating correctly, but the updated radio checked states are not updating in to the UI. So I have set it using javacript on the Onload event of a body.
Add the Onload event on the body.
<body onload="setRadioButonStatus()">
and add the following Javascript.
function setRadioButonStatus() {
var rbtn1 = document.getElementById('RadioButton1');
var rbtn2 = document.getElementById('RadioButton2');
if (rbtn1.hasAttribute("checked"))
rbtn1.checked = true;
if (rbtn2.hasAttribute("checked"))
rbtn2.checked = true;
}
Seems like you aren't creating a "default" scenario. You can do this, and tie the logic together more closely by doing something like this on every Page_Load and leaving it out of your event.
protected void Page_Load(object sender, EventArgs e)
{
GV_addition.Visible = RadioButtonList1.SelectedIndex == 0;
GV_termination.Visible = RadioButtonList1.SelectedIndex == 1;
}
protected void RadioButtonList1_SelectedIndexChanged(object sender, EventArgs e)
{
}

Execute Text Box_TextChanged Event in Asp.Net using C#?

I am trying to implement validations on textbox like if null then display a message to fill the empty field and to check the length of the text entered. I have written the code for it inside TextBox_TextChanged event but it's not working. The event is not getting fired and the user can is able to signup without a username, that is my problem at the moment. Do I have to trigger the event manually? Here is a glimpse of what I am doing:
protected void FirstN_TextBox_TextChanged(object sender, EventArgs e)
{
String firstNameEntered = FirstN_TextBox.Text;
if (firstNameEntered != null)
{
if (firstNameEntered.Length <= 20)
{
MessageBox.Show("Inside text box");
}
else
{
}
}
else
{
FirstN_TextBox.Focus();
MessageBox.Show("Please fill the marked field");
}
change it like this:
From:
<asp:TextBox ID="FirstN_TextBox" placeholder="First name" runat="server" Width="225px" OnTextChanged="FirstN_TextBox_TextChanged"></asp:TextBox>
To:
<asp:TextBox ID="FirstN_TextBox" placeholder="First name" runat="server" Width="225px" OnTextChanged="FirstN_TextBox_TextChanged" AutoPostBack ="true"></asp:TextBox>

Validation of a textbox, so that the value differed from another textbox

I want to validate a textbox, so that the Text value of firstNameTextBox differed from nicknameTextBox. I'm using InitialValue property of RequiredFieldValidator, like this -
fieldValidatorInitialValue.InitialValue = firstNameTextBox.Text;
Here is the code:
RequiredFieldValidator fieldValidatorInitialValue = new RequiredFieldValidator();
TextBox firstNameTextBox = new TextBox();
TextBox nicknameTextBox = new TextBox();
protected void Page_Load(object sender, EventArgs e)
{
Button submitButton = new Button();
submitButton.CausesValidation = true;
submitButton.Click += submitButton_Click;
nicknameTextBox.ID = "nickname";
firstNameTextBox.ID = "firstname";
fieldValidatorInitialValue.ControlToValidate = firstNameTextBox.ID;
}
protected void submitButton_Click(object sender, EventArgs e)
{
fieldValidatorInitialValue.InitialValue = nicknameTextBox.Text;
}
However, using this code the validation doesn't work correctly, only after the second click on button. I also tried to put all of the RequiredFieldValidator code to submitButton_Click event handler, however it doesn't work at all in this case, could someone please help me with it?
Try this.you should use CompareValidator instead of RequiredFieldValidator, with Operator="NotEqual"
<asp:CompareValidator runat="server"
ControlToValidate="tbFName"
ControlToCompare="tbLName"
Type="String"
Operator="NotEqual"
ErrorMessage="First and last name cannot be the same" />
Try below code
protected void Page_Load(object sender, EventArgs e)
{
if(!IsPostBack)
{
Button submitButton = new Button();
submitButton.CausesValidation = true;
submitButton.Click += submitButton_Click;
nicknameTextBox.ID = "nickname";
firstNameTextBox.ID = "firstname";
fieldValidatorInitialValue.ControlToValidate = firstNameTextBox.ID;
}
}
I think the way you are trying to compare "First name" and "Nick
Name" is unnecessarily complex.
Instead of that you can simply use CompareValidator and achieve the same task on single button click. Here , Add this on your
designer page:
<asp:CompareValidator ID="comNames" runat="server"
ControlToValidate="firstNameTextBox"
ControlToCompare="nicknameTextBox"
ErrorMessage="Error: Name cant be same"
SetFocusOnError="True" Text="*"></asp:CompareValidator>
In case you want to add Validator dynamically, Add CompareValidator
instead of RequiredFieldValidator and add following properties:
ControlToValidate="firstNameTextBox"
ControlToCompare="nicknameTextBox"
ErrorMessage="Error: Name cant be same"
SetFocusOnError="True"
Text="*"
Note: if you are using ValidationGroup for button,use same name of
ValidationGroup for Validator also.

How to display remaining textbox characters in a label in 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

How can I access DataGridRow from a textbox on that row?

In a DataGrid, when text in a textbox changes I want to add the value of another field in that row to an array.
public void txtTitle_TextChanged(object sender, EventArgs e)
{
TextBox titleBox = (TextBox)sender;
DataGridItem myItem = (DataGridItem)titleBox.Parent.Parent;
string test = DataBinder.Eval(myItem.DataItem, "prod_id").ToString();
}
However myItem.DataItem evaluates as null. I was expecting it to evaluate as DataRowView?
You can get the TextChanged event to fire if you do the following:
<asp:DataGrid ID="DataGrid1" runat="server" AutoGenerateColumns="False"
onitemdatabound="DataGrid1_ItemDataBound">
<Columns>
<asp:TemplateColumn HeaderText="Test">
<ItemTemplate>
<asp:TextBox OnTextChanged="txtBox_TextChanged" ID="TextBox1" runat="server" AutoPostBack="True"></asp:TextBox>
</ItemTemplate>
</asp:TemplateColumn>
<asp:BoundColumn DataField="Name" HeaderText="Test 1"></asp:BoundColumn>
</Columns>
</asp:DataGrid>
You will notice that i have the following properties set:
AutoPostBack="True"
I have also manually added the OnTextChanged="txtBox_TextChanged" to the text box as well.
In my code behind i have:
protected void txtBox_TextChanged(object sender, EventArgs e)
{
TextBox txtBox = (TextBox)sender;
Label1.Text = txtBox.Text;
}
The only way the event will fire is when you lose focus on the text box after typing.
Key points to consider:
This will cause a post back, so Ajax might be a good way to keep the user experience nice.
You will need to make sure you wrap your DataBind() in a if (!IsPostBack)
Hope this helps!
Effectively, I solved this by adding an autonumber column to the table, and using the value of this to determine the row's positino in the table, then using the value of this to affect the appropriate row in the datagrid.
I'm now merely changing the color of the row rather than adding values in that row to an array, as stated in the original question.
public void txtPrice_TextChanged(object sender, EventArgs e)
{
TextBox txtPrice = (TextBox)sender;
DataGridItem myItem = (DataGridItem)txtPrice.Parent.Parent;
markRows(myItem, true);
}
public void markRows(DataGridItem myItem, bool toSave)
{
// Prepeare to save this record?
CheckBox thisSave = (CheckBox)myItem.FindControl("chkSave");
thisSave.Checked = toSave;
// Establish the row's position in the table
Label sNo = (Label)myItem.FindControl("SNo");
int rowNum = Convert.ToInt32(sNo.Text) - 1;
CheckBox rowSave = (CheckBox)grid.Items[rowNum].FindControl("chkSave");
// Update background color on the row to remove/add highlight
if (rowSave.Checked == true)
grid.Items[rowNum].BackColor = System.Drawing.Color.GreenYellow;
else
{
Color bgBlue = Color.FromArgb(212, 231, 247);
grid.Items[rowNum].BackColor = bgBlue;
// some code here to refresh data from table?
}
}

Categories