I am developing an application in ASP.NET & c#. I have a Grid view in my page. In that I have a Listbox control and by default Enabled property set by false. I am trying to enable & disable that control from javascript / jQuery on Checkbox control.
My ASP Code:
<asp:GridView ID="gvWhom" runat="server" AutoGenerateColumns="False" DataSourceID="odsWhom"
GridLines="None" Width="100%" OnRowDataBound="gvWhom_RowDataBound">
<Columns>
<asp:TemplateField>
<HeaderTemplate>
</HeaderTemplate>
<ItemTemplate>
<table width="100%" cellpadding="0" cellspacing="0" border="0">
<tr style="height: 25px;">
<td width="20%">
<asp:CheckBox ID="chkCriteria" runat="server" Text='<%#Eval("TargetType") %>' />
</td>
<td width="80%">
<asp:ListBox ID="lbCriteria" runat="server" CssClass="ddl" Width="150px" Height="50px"
Enabled="false" SelectionMode="Multiple"></asp:ListBox>
</td>
</table>
</ItemTemplate>
<HeaderStyle Height="2px" />
</asp:TemplateField>
</Columns>
</asp:GridView>
Javascript Code:
function disableDropDown(chkCriteria, lbCriteria) {
if (document.getElementById(chkCriteria).checked) {
document.getElementById(lbCriteria).removeAttribute('disabled');
}else{
document.getElementById(lbCriteria).value = -1;
document.getElementById(lbCriteria).disabled = true;
}
return true;
}
C# Code:
protected void gvWhom_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
ListBox lbCriteria = (ListBox)e.Row.FindControl("lbCriteria");
CheckBox chkCriteria = (CheckBox)e.Row.FindControl("chkCriteria");
chkCriteria.Attributes.Add("onchange", "javascript:return disableDropDown('" + chkCriteria.ClientID + "', '" + lbCriteria.ClientID + "')");
}
}
Using above code I am able to enable / disable the Listbox control. But when I enable the control and select multiple items and submitting the form I am not able to find selected items of Listbox.
How can I fetch selected items of Listbox? or Is there any other way to enable - disable the listbox control and get the selected items in c# code?
This is mostly a guess, but it's worth a try...
You're disabling the control on the server-side here:
<asp:ListBox ID="lbCriteria" runat="server" CssClass="ddl" Width="150px" Height="50px"
Enabled="false" SelectionMode="Multiple"></asp:ListBox>
That Enabled="false" may be indicating to ASP.NET that it doesn't need to track this control, that changes won't be made to it. That might be why it's not getting the data back when you post back to the server.
Let's try keeping the control enabled from the server's (ASP.NET's) perspective, and maintaining the enabling/disabling in the UI entirely on the client's (JavaScript's) side. Essentially removing ASP.NET's built-in framework from making decisions for you regarding what data to track.
Start by enabling the control in the server-side control markup:
<asp:ListBox ID="lbCriteria" runat="server" CssClass="ddl" Width="150px" Height="50px"
SelectionMode="Multiple"></asp:ListBox>
The rest is handled by JavaScript. You already have some JavaScript code which you say enables/disabled the control on the client-side for you, correct? So all you need to do now is call that same JavaScript for every instance of the control when the page first loads in the browser to disable the controls client-side. This is the part you want:
document.getElementById(lbCriteria).value = -1;
document.getElementById(lbCriteria).disabled = true;
Now, it looks like you're binding your JavaScript events from the server-side code, which is where I won't be able to help as much because that method isn't particularly intuitive to me. (It's mixing JavaScript and C#, which feels a bit backwards.) So I'm not entirely sure the approach you'd take there.
Essentially you want to invoke those two lines of JavaScript for every instance of the control, and you want it to happen as soon as the page loads in the browser.
In jQuery I'd do something like this:
$(function () {
$('select.ddl').attr('disabled', 'disabled');
});
This would run when the DOM is loaded and would add the disabled attribute (with a value of "disabled" to every select with the class ddl.
Related
I have a FormView that has elements that I want to make available to different users depending on the users access permissions. I have encased each of these inside of a panel and ID'd the panel so that I can call them out from the code behind potentially drilling into the FormView with FindControl but have been unsuccessful so far in getting it worked out.
I've never had much luck with FindControl and was wondering if some of you that are more knowledgeable about it could point me in the right direction here is an example of my code on the aspx and C# code behind that IS NOT working out!
If this were functioning then I would place conditionals to for valid groups under this protected void for this panel to allow these users access to this panel and likewise do the same for other panels where permission was applied.
In this way I would be presenting a custom FormView for each user group based on my ACL. But I just can't get through my head how to drill in with the FindControl properly.
ASPX SAMPLE:
<asp:FormView Width="100%" ID="ChangeFormFV" DefaultMode="Insert" runat="server" DataKeyNames="CAssetID" DataSourceID="UpdateSqlDataSource">
<InsertItemTemplate>
<asp:Panel runat="server" ID="ShortDescPnl" Visible="false">
</asp:Panel>
<asp:Panel runat="server" ID="LongDescPnl" Visible="false">
</asp:Panel>
<asp:Panel runat="server" ID="AddNotesPnl" Visible="false">
</asp:Panel>
<asp:Panel runat="server" ID="ManufacturerPnl" Visible="false">
</asp:Panel>
<asp:LinkButton runat="server" Text="Insert" CommandName="Insert" ID="InsertButton" CausesValidation="True" /> <asp:LinkButton runat="server" Text="Cancel" CommandName="Cancel" ID="InsertCancelButton" CausesValidation="False" />
</ItemTemplate>
C# Codebehind (not working):
protected void ChangeFormFV_Databound(object sender, EventArgs e)
{
if (Session["SessionUType"].ToString() == "ITSec")
{
ChangeFormFV.Row.FindControl("ShortDescPnl.visiblity")="true";
}
}
Appreciate any help that can be offered, been searching for references and reading all I can but just not getting what I need from my results.
The FindControl method returns the actual control. Set the visibility on the control itself. Something like this:
Panel control = ChangeFormFV.Row.FindControl("ShortDescPnl") as Panel;
if (control != null)
control.Visible = true;
I have two buttons inside of the repeater and I'm trying to access them from code behind, but they are not working. I receive the following error:
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.
I don't understand what does the error mean nor where is coming from. Here is my code:
<asp:Repeater ID="Repeater1" runat="server"
onitemdatabound="Repeater1_ItemDataBound1"
onitemcommand="Repeater1_ItemCommand" >
<ItemTemplate>
<table>
<tr>
<td><asp:Image ID="Image1" runat="server" /></td>
<td><asp:Label ID="empnamelbl" runat="server" Text='<%# Eval("fullname") %>'></asp:Label></td>
<td><asp:DropDownList ID="DropDownList1" runat="server">
</asp:DropDownList></td>
<td> <asp:Button ID="Button1" runat="server" Text="Present" CommandName="test1" CommandArgument='<%# Eval("ID") %>' /> </td>
<td><asp:Button ID="Button2" runat="server" Text="Absent" CommandName="test2" CommandArgument='<%# Eval("ID") %>' /> </td>
</tr>
</table>
</ItemTemplate>
</asp:Repeater>
Code behind:
protected void Repeater1_ItemCommand(object source, RepeaterCommandEventArgs e)
{
if (e.CommandName == "test1")
{
Response.Write("hi");
}
}
I was able to solve it by using, UseSubmitBehavior="false", property in the buttons.
Here is it:
<asp:Button ID="Button2" UseSubmitBehavior="false" runat="server" Text="Absent" CommandName="test2" CommandArgument='<%# Eval("ID") %>' />
Try setting EnableViewState="false" for the repeater. Definitely there will be some drawbacks but this has worked for me.
Else below are some more approaches you can try on:
If you are setting your Repeater's DataSource in Page_Load event.
Try wrapping your Page_Load code inside if(!IsPostBack) .
protected void Page_Load( object sender , eventArgs e)
{
if(!IsPostBack)
{
// bind repeater , dropdownlist items ... here
}
}
Also from your error message it seems that enableEventValidation=“true” setting is present either in your Page as:
<%# Page EnableEventValidation="true" ... %>
OR in your web.config :
<system.web>
<pages enableEventValidation="true"/>
</system.web>
Some suggestions:
Disable eventvalidation. Easy to do but less secure .THIS IS NOT RECOMMENDED. Also read here an extremely good article on this issue: http://odetocode.com/blogs/scott/archive/2006/03/22/asp-net-event-validation-and-invalid-callback-or-postback-argument-again.aspx
If any client side method is used to set changes in Controls, It's better to use the
postback and add or remove the items server-side. Example: if a list control includes options numbered 1, 2, or 3 when the page is rendered, and if a postback request is received specifying option number 4, ASP.NET raises an exception.
This MSDN reference. is good too.
I hope this helps.
due to presence of Image that run at server .. try to use img tag instead
Is it possible to programatically insert C# Inline Expressions as the values for ASP.NET Controls in your server-side code?
I'm currently using a DataList to display a lot of data in a table. I want to be able to dynamically change the columns of that table, so I need to be able to edit what controls are in its ItemTemplate.
However, in addition to editing the controls in the ItemTemplate, I need to be able to alter the value that is binded to each control in the template, because I want to dynamically change what is being displayed.
So what I currently have is a static table that doesn't change:
<asp:DataList ID="dataList" runat="server" OnSelectedIndexChanged="dataList_OnSelectedIndexChanged" DataSourceID="peopleData">
<ItemTemplate>
<table>
<tr>
<td>
<asp:LinkButton ID="NameLink" OnClientClick="onPageUpdate()" CommandName="Select" Text='<%# Eval(this.Name) %>' ForeColor='<%# Eval("this.NameColor") %>' runat=Server" />
</td>
<td>
<asp:Label Text='<%# Eval("this.Values[\"Age\"]") %>' ForeColor='<%# Eval("this.ValueColors[\"Age\"]") %>' runat="Server">
</td>
// OTHER COLUMNS WITH DIFFERENT DATA
</tr>
</table>
</ItemTemplate>
</asp:DataList>
// OBJECT DATA SOURCE CODE
I know how to dynamically add Controls to the ASPX web page. However, I don't know how to add the inline expressions.
I've tried doing the following but it doesn't work because of the type mismatches:
Label label = new Label();
label.Text = "<%# Eval(\"this.Values[\\\"Age\\\"]\") %>";
label.ForeColor = "<%# Eval(\"this.ValueColors[\\\"Age\\\"]\") %>";
Is there a way of achieving this or doing something similar?
My only other option that I can think of right now is to scrap using the DataList and ItemTemplate and just generate each row myself.. That's a lot more coding versus just using the ItemTemplate.
Not sure if this would help you, but look at http://msdn.microsoft.com/en-us/library/system.web.ui.databinder(v=vs.100).aspx
It is showing using of the hand-written exposure of properties. If your property were always call "magic" and you return the appropriate value for magic within your code would that get you what you need?
I have a search form in an updatePanel which retrieves a list of users in a grid in the same UpdatePanel. The name of each user is a commandLink. I want to make the commandLinks as PostBackTriggers.
But when I do it I get an error at the pageLoad time that the controlId does not exist and its true because the grid of users does not render at the load time but through an ajax call.
Any ideas on how can I make the multiple command buttons in a grid retrieved through ajax call as post back triggers?
When adding the items to the grid, within the ItemDataBound event handler, you should register the postback for each specific control (the static identifiers in your HTML declarations are essentially placeholders - not all things repeated in the grid can actually have the same ID). You do this using the ScriptManager.RegisterAsyncPostBackControl method:
The RegisterAsyncPostBackControl method enables you to register Web
server controls as triggers so that they perform an asynchronous
postback instead of a synchronous postback. When the
ChildrenAsTriggers property of an UpdatePanel control is set to true
(which is the default), postback controls inside the UpdatePanel
control are automatically registered as asynchronous postback
controls.
As stated above, using ChildrenAsTriggers is a possibility, too, but this is commonly set to false for more stringent management.
I have found the solution. Here is the code on asp
<asp:UpdatePanel ID="UpdatePanel1" runat="server">
<ContentTemplate>
<asp:TextBox ID="txtFirstName" runat="server"></asp:TextBox>
<asp:Button ID="btnSearch" runat="server" OnClick="btnSearch_Click" Text="Search" />
<asp:GridView ID="gvSearchResult" runat="server" OnRowCommand="gvSearchResult_RowCommand"
OnRowDataBound="gvSearchResult_RowDataBound">
<Columns>
<asp:TemplateField HeaderText="Name">
<ItemTemplate>
<asp:LinkButton ID="lnkbtnDetail" runat="server" CommandArgument='<%# Bind("CNIC") %>' CommandName="Detail">
<asp:Label ID="lblName" Text='<%# Bind("Employee_Name") %>' runat="server</asp:Label>
</asp:LinkButton>
</ItemTemplate>
<ItemStyle HorizontalAlign="Left" VerticalAlign="Middle"Height="25px"Width="30%" />
</asp:TemplateField>
</Columns>
</asp:GridView>
Ihad to place OnRowDataBound="gvSearchResult_RowDataBound" on gridView and that function looks like below. So I had to register the iterative control in Scriptmanager as PostBackControl in RowDataBound event of GridView.
protected void gvSearchResult_RowDataBound(object sender, GridViewRowEventArgs e)
{
try
{
if ((e.Row.RowType == DataControlRowType.DataRow))
{
LinkButton lnkbtnDetail = (LinkButton)e.Row.FindControl("lnkbtnDetail");
ScriptManager.GetCurrent(this).RegisterPostBackControl(lnkbtnDetail);
}
}
catch (Exception ex)
{
}
}
I have the following DataList-
<td>
<asp:Label ID="Label3" runat="server" Text="Exclude"></asp:Label>
<asp:DataList runat="server" ID="excludeTextBox">
<ItemTemplate>
<br />
<asp:TextBox ID="myTextBox" runat="server" Text='<%# Container.DataItem.ToString() %>'></asp:TextBox>
</ItemTemplate>
</asp:DataList>
<td>
<asp:Label ID="Label4" runat="server" Text="Active"></asp:Label>
<asp:DataList runat="server" ID="activeCheck" >
<ItemTemplate>
<br />
<asp:CheckBox ID="CheckBox1" runat="server" Checked='<%# Container.DataItem.ToString().Equals("1") %>' OnCheckedChanged="CheckBox1_CheckedChanged" AutoPostBack="true" />
</ItemTemplate>
</asp:DataList>
</td>
So this is generating a textBox and checkBox for every row that exits in the database.
Currently there is no save action associated with the dataList, however if a user checks or unchecks one of the checkBoxes this calls a webservice and toggles the value in a data base table.
My question is, after a user has edited the text in some of the textBoxes and checked or unchecked some of the check boxes, how can I catch the changes in a save changes button. Because if the items have been dynamically created then technically they do not exist on the page. I want to do this without having a save option on ever row on the dataList.
protected void saveChanges_Click(object sender, EventArgs e)
{
// capture all edits and call update webservice method.
}
You'd essentially have to build the representation of the changes. Because there is no generic solution to this, I don't have any code, but here is the process:
As an item changes, you have to store what changed. You could store the indexes of the rows that actually changed in a hidden variable on the page, or store the changes in a JavaScript object. When save changes is clicked, on the client you then loop through these changes, and if they exist send them in bulk or one at a time.
If you had a hidden field with a value like 0,2,5 for each index that changed, you could easily find those items, grab the values from the form, and ship them off to the web service. Or, you could build a JavaScript object that has the changes like:
{ key: 2, checked: true, text:"My new text" }
Store these in an array, and push them up to the server through the web service.