This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
JQUERY: Finding by control ID
as i am trying set label id using <%# Eval("SomeColumnName") %>. i wonder is it possible? i need to give LabelID with Some Suffix, like UserID.
eg : <asp:Label Id="ss_<%# Eval("UserID") %>" runat="server" />
i have placed this in gridview. so it will generate random id, based on the container_control_somerow_someID format, i thought will assign UserID at the end of the so that it will be unique. then i can easily get the client id easily, by using indexof method.
i have a label in gridview, and beside of label i have a button. whenever i click the button, i need to send the label text or id.
is it possible ? right now it is giving error, as Asp.net markup are not well formed. if not possible can any body tell me, what is the reason behind this to not allowed to assign like this ?
can anybody tell me ?
Does it have to be an asp:Label and runat=server? If not you could do it with a plain label (or span).
<label id='ss_<%# Eval("UserID") %>' />
Note the quotes.
For your requirement you can use RowCommand of ASP.NET will help
<asp:GridView id="grdCommodityTypeSize" runat="server" AllowPaging="True"
AllowSorting="True" AutoGenerateColumns="False"
DataKeyNames="nCommodityTypeSizeID" EnableViewState="False" Width="500px"
DataSourceID="odsCommodityTypeSize" PageSize="8"
OnRowDataBound="grdCommodityTypeSize_RowDataBound"
OnRowUpdating="grdCommodityTypeSize_RowUpdating"
OnRowDeleted="grdCommodityTypeSize_RowDeleted"
OnRowUpdated="grdCommodityTypeSize_RowUpdated"
OnRowCommand="grdCommodityTypeSize_RowCommand">
<asp:Button ID="btnTypeSizeCommodity1" runat="server" Text="Go"
CommandName="Go" CommandArgument='<%# Eval("nCommodityTypeSizeID") %>' />
</asp:GridView>
and in the code behind you can go for
if (e.CommandName.ToUpper() == "GO")
{
int _rowIndex = -1;
Button btn = (Button)e.CommandSource;
for (int i = 0; i < grdCommodityTypeSize.DataKeys.Count; i++)
{
if (Convert.ToInt32(grdCommodityTypeSize.DataKeys[i].Value) ==
Convert.ToInt32(e.CommandArgument))
{
_rowIndex = i;
break;
}
}
if (_rowIndex > -1)
{
//ur code
}
}
you will get the row from which button is clicked. You can get the row and manipulate watever u want.
Related
When I'm trying to get a value from a textbox I keep getting this error (see image) and I don't know how to fix it. I'm using the following code:
protected void Button3_Click(object sender, EventArgs e)
{
_controller = new Controller();
//Variablen
string afspraak ="";
foreach (GridViewRow row in GridView1.Rows)
{
afspraak = ((TextBox)row.FindControl("txtEditTabel")).Text;
}
I'm using javascript combined with ASP.NET and the code looks like this;
more info about the js: EDITABLE LABEL
JAVASCRIPT (it changes a label to a textbox on click)
$(function () {
//Loop through all Labels with class 'editable'.
$(".editable").each(function () {
//Reference the Label.
var label = $(this);
//Add a TextBox next to the Label.
label.after("<input type = 'text' style = 'display:none' />");
//Reference the TextBox.
var textbox = $(this).next();
//Set the name attribute of the TextBox.
var id = this.id.split('_')[this.id.split('_').length - 1];
//textbox[0].name = id.replace("Label","Textbox"); //tis dit hier van die id's
textbox[0].name = "txtEditTabel";
//Assign the value of Label to TextBox.
textbox.val(label.html());
//When Label is clicked, hide Label and show TextBox.
label.click(function () {
$(this).hide();
$(this).next().show();
});
//When focus is lost from TextBox, hide TextBox and show Label.
textbox.focusout(function () {
$(this).hide();
$(this).prev().html($(this).val());
$(this).prev().show();
});
});
});
ASP.NET
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" CellPadding="4" ForeColor="#333333" GridLines="None" Width="1000px" HorizontalAlign="Center" OnSelectedIndexChanged="GridView1_SelectedIndexChanged">
<AlternatingRowStyle BackColor="White" ForeColor="#284775" />
<Columns>
<asp:TemplateField HeaderText="IDAfspraken">
<ItemTemplate>
<asp:Label ID="Label4" runat="server" Text='<%# Eval("IDAfspraken") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
</asp:GridView>
I'm 100% sure that my SQL code is correct. Am I missing something? I'd really appreciate the help!
Error:
The value for ((TextBox)row.FindControl("txtEditTabel")) appears to be returning a null or undefined value, hence the NullPointerException, when trying to dereference the .Text property.
Your use case seems really specific to your C# code, moreso than the JavaScript. My best guess is that you should try adding an id property to your control rather than a name. I could be wrong, but judging by the specs found here on FindControl method, you should be accessing the control by ID instead of name.
Edit:
If your input is inside of a form, try accessing it via the input's name property with the following syntax: Request.Form["txtName"]; instead of trying to do a FindControl.
I have Parent repeater which contains another child repeater.
For simplicity let's say that the child repeater contains text box and Requiredvalidator.
Simple example of the markup:
<asp:Repeater ID="rpt1" runat="server">
<HeaderTemplate>
....
</HeaderTemplate>
<ItemTemplate>
<asp:Label ID="lbl1" runat="server" CssClass=".."></asp:Label>
<div class="..">
<asp:Repeater ID="rpt2" runat="server">
<HeaderTemplate>
</HeaderTemplate>
<ItemTemplate>
<div class="...">
<asp:TextBox ID="txt21" runat="server" CssClass="..." MaxLength="7" CssClass="ErrorMessage" ErrorMessage="*" />
<asp:RequiredFieldValidator ID="rfv21" runat="server" CssClass="ErrorMessage" ErrorMessage="*" />
</div>
</ItemTemplate>
<FooterTemplate>
</FooterTemplate>
</asp:Repeater>
</div>
</ItemTemplate>
<FooterTemplate>
</FooterTemplate>
</asp:Repeater>
I create a method like this to get the second repeater's RequiredField id:
function getId(){
var myId = document.getElementById('<%= rfv21.ClientID %>');
}
but of course it didn't work and there was an exception:
The name control-name Does Not Exist in the Current Context
So how can i do this?
I want to mention that the business need for me is that when the onchange, onkeyup, onkeydown events fires for the txt21 it will get it's equivalent rfv21 and enbale it:
I create this method which fires for onchange, onkeyup, onkeydown events changed:
function txt21_onChange(txtbox) {
var newValue = this.value;
var oldValue = this.oldvalue;
var myRfv2 = document.getElementById('<%= rfv2.ClientID %>');
if (newValue != oldValue) {
ValidatorEnable(myRfv2, true);
}
}
and i update txt21 to be:
<asp:TextBox ID="txt21" runat="server" CssClass=".." MaxLength="7" onkeyup="javascript: txt21_onChange(this);this.oldvalue = this.value;" />
but this line want work:
var myRfv2 = document.getElementById('<%= rfv2.ClientID %>');
as i explained before.
I think Item.FindControl(..) may help but how can we use it in this case?
You can bind the javascript function call from Repeater Repeater.ItemDataBound event.
Code Bahind
void R1_ItemDataBound(Object Sender, RepeaterItemEventArgs e)
{
if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem)
{
TextBox txt21 = (TextBox)e.Item.FindControl("txt21");
RequiredFieldValidator rfv21 = (RequiredFieldValidator)e.Item.FindControl("rfv21");
txt21.Attributes.Add("onclick", "txt21_onChange('" + txt21.ClientID + "','" + rfv21.ClientID + "'" )
}
}
Javascript
function txt21_onChange(txt21ID, rfv21ID)
{
txt21ID = document.getElementById(txt21ID);
rfv21ID = document.getElementById(rfv21ID);
//The above are TextBox and RequiredFieldValidator objects of row of TextBox that triggered change event.
//You can use these object
}
The problem here is that there going to be many such controls, one per each row of each child repeater. All will have slightly different generated IDs. So instead of querying them by id (impossible), you can use jQuery to quickly find them relatively to the txt that fired an event:
function txt21_onChange(txtbox) {
var rfv2 =
$(textbox) // gives you the jquery object representing the textbox
.closest("div") // the parent div
.find("id*='rfv2'"); // the element you are looking for, id contains rfv2
This answers the immediate question in this thread on how to get hold of the element. But I am not sure it will solve your bigger problem of enabling/disabling validation. You cannot easily do so with server side controls in javascript. Besides, validator is not disabled by default in your code. Although I believe all this is worth a separate question here on SO>
I have four text boxes in 4 different tabs of an ASP.NET Page. I need to provide same validation message to all the text boxes. Presently I am using four different functions with same functionality. Kindly suggest a way to identify which textbox is being used make that a single funtion
Code from Commend:
<asp:TextBox ID="textBox1" runat="server" ValidationonGroup="abcd"></asp:TextBox>
<asp:CustomValidator ID="ID1" runat="server" ValidationGroup="abcd"
ControlToValidate="textBox1" ErrorMessage="message"
ClientValidationFunction="fname"></asp:CustomValidator>
--Javascript Fn--
function fname(sender, args) {
var x = document.getElementById('<%=txtBox1.ClientID%>').value;
if (some condition) {
args.IsValid = false;
} else {
args.IsValid = true;
}
}
Edit
if you are using Asp.Net then you should use like this
Aspx page code
<div>
<asp:TextBox runat="server" ID="txt1" ClientIDMode="Static" onKeyPress="javascript:text_changed(this.id);"></asp:TextBox>
</div>
JS Code
<script type="text/javascript">
function text_changed(event)
{
var id = event;
alert(id);
}
</script>
You got the textbox id in id variable and now u can get value etc using this id you are applying your conditions.... i hope this will help u
Good day,
I have a repeater that contain link button. The value and number of link button is generate base on data pull from database. The HTML code is something as follow:
<asp:Repeater ID="repCategories" runat="server" EnableViewState="false">
<ItemTemplate>
</ItemTemplate>
</asp:Repeater>
Here is some code that I try to do in my code behind,
for (int i = 0; i < table.Rows.Count; i++)
{
RepeaterItem itm = repCategories.Items[i];
GiftRow dr = tbl.GetRow(i);
Literal litLink2 = (Literal)itm.FindControl("litLink2");
litLink2.Text = dr.Name;
string myScript = string.Empty;
myScript = "\n<script type=\"text/javascript\" language=\"Javascript\" id=\"EventScriptBlock\">\n";
myScript += "alert('hi');";
myScript += "\n\n </script>";
Page.ClientScript.RegisterStartupScript(this.GetType(), "myKey", myScript, false);
}
By doing this, I will get alert hi when I load the page.What I want to do is, I only want it do alert hi when I click on the link button, instead of page load.
Use a LinkButton and leverage the ClientClick event instead:
<asp:Repeater ID="repCategories" runat="server" EnableViewState="false">
<ItemTemplate>
<asp:LinkButton ID="lbMyLinkButton" runat="server" />
</ItemTemplate>
</asp:Repeater>
I'd also recommend you use ItemDataBound events of repeaters where possible:
void repCategories_ItemDataBound(Object Sender, RepeaterItemEventArgs e) {
if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem) {
((LinkButton)e.Item.FindControl("lbMyLinkButton")).OnClientClick = "alert('hi');";
}
}
NOTES:
I wouldn't ever recommend you render javascript server-side unless absolutely necessary. I've provided an answer to fit in with the context of your question, but I would advise you have a javascript function already on your page and 'wire it up' server-side (if not bind it on the client with pure javascript)
There is also an assumption here that you're binding data to the repeater (you should be anyway), which means you also have to wire up the ItemDataBound handler: repCategories.OnItemDataBound += repCategories_ItemDataBound
I am trying to use JavaScript to set a textbox text equal to "" or NULL. I am using visual studio 2013 and have created an asp.net web application. I am also using telerik controls(not sure if that will affect anything). I currently have a combobox(ddlMaritalStatus) and a textbox(txtSpouseName). I currently have JavaScript that when ddlMaritalStatus selected text is set to single then txtSpouseName is disabled. I would also like to have txtSpouseName have its text erased when ddlMaritalStatus is changed back to single. I have been researching through Google and through stack overflow and have not come across an option that works. Every answer I have found says to use document.getElementById("txtSpouseName").value = ""; but my program is not reading the .value with JavaScript.
<telerik:RadComboBox ID="ddlMaritalStatus" runat="server" EmptyMessage="--Select--" OnClientSelectedIndexChanged="DisableBox" TabIndex="15" AutoPostBack="false"></telerik:RadComboBox>
<script type="text/javascript">
function DisableBox() {
var TextBox = $find("<%=txtSpouseName.ClientID %>");
var Location = $find("<%=ddlMaritalStatus.ClientID %>");
if (Location.get_text().length < 7) {
TextBox.disable();
document.getElementById("txtSpouseName").value = "";
}
else {
TextBox.enable();
}
}
</script>
<telerik:RadTextBox ID="txtSpouseName" runat="server" Enabled="false" AutoPostBack="false" TabIndex="16"></telerik:RadTextBox>
Here is the code that I have so far. Any help or suggestions would be great! Thanks!
EDIT
I am using IE 11.
Please try with the below code snippet.
<script type="text/javascript">
function ClientSelectedIndexChanged(sender, args) {
if (sender.get_selectedItem().get_value() == "Single") {
document.getElementById(sender.get_id().replace("ddlMaritalStatus", "txtSpouseName")).value = "";
document.getElementById(sender.get_id().replace("ddlMaritalStatus", "txtSpouseName")).disabled = "disabled";
}
else {
document.getElementById(sender.get_id().replace("ddlMaritalStatus", "txtSpouseName")).value = "";
document.getElementById(sender.get_id().replace("ddlMaritalStatus", "txtSpouseName")).disabled = "";
}
}
</script>
...........
...........
<asp:Panel ID="Panel1" runat="server">
<telerik:RadComboBox ID="ddlMaritalStatus" runat="server" OnClientSelectedIndexChanged="ClientSelectedIndexChanged">
<Items>
<telerik:RadComboBoxItem Value="Married" Text="Married" />
<telerik:RadComboBoxItem Value="Single" Text="Single" />
</Items>
</telerik:RadComboBox>
<asp:TextBox ID="txtSpouseName" runat="server"></asp:TextBox>
</asp:Panel>
Let me know if any concern.
This is the answer I found from another post. This disables the textbox when "Married" is selected and erases and disable the textbox when "Single" is selected. Thank you to everyone who tried to help me!
function DisableBox(sender, args) {
var TextBox = $find("<%=txtSpouseName.ClientID %>");
if (args.get_item().get_text() == "Married") {
TextBox.enable();
}
else {
TextBox.clear();
TextBox.disable();
}
}