Link Button have some Problems - c#

I have one ASP.NET application which includes one gridview. This gridview contains 4 template columns of checkboxes and 2 template columns of link buttons. If I click on the first checkbox, then both of the link buttons should be enabled, otherwise they should be in disabled mode. This functionality is working fine. But my problem is, at the time of form loading, it will check whether the first column is checked or not. If the checkbox is not checked, the link buttons will be in disabled mode. But after the checking of this checkbox, it will enabled, but there is no link to redirect. My code is shown below.
protected void DGDocuments_ItemDataBound(object sender, DataGridItemEventArgs e)
{
if (e.Item.ItemIndex == -1) return;
BindCheckBox(e.Item, "chkRead");
BindCheckBox(e.Item, "chkCreate");
BindCheckBox(e.Item, "chkUpdate");
BindCheckBox(e.Item, "chkDelete");
CheckBox chkID = (CheckBox)e.Item.FindControl("chkRead");
if (!chkID.Checked)
{
LinkButton lnkPermission = (LinkButton)e.Item.FindControl("lnkFieldPermssion");
LinkButton lnkSetRules = (LinkButton)e.Item.FindControl("lnkAddRules");
lnkPermission.Enabled = false;
lnkSetRules.Enabled = false;
}
}
In designer page:
<asp:TemplateColumn HeaderText="Read" ItemStyle-HorizontalAlign="Center">
<ItemTemplate>
<asp:CheckBox ID="chkRead" runat="server" Text='<%# Eval("Read") %>' onclick="javascript:EnablePermissoin(this,5,6);" />
</ItemTemplate>
</asp:TemplateColumn>
<asp:TemplateColumn HeaderText="Rules" ItemStyle-HorizontalAlign="Center" ItemStyle-Font-Bold="true">
<ItemTemplate>
<asp:LinkButton ID="lnkAddRules" Text="Add Rules" runat="server" CommandName="cmdSetRules" />
</ItemTemplate>
</asp:TemplateColumn>
<asp:TemplateColumn HeaderText="Field Permission" ItemStyle-HorizontalAlign="Center" ItemStyle-Font-Bold="true">
<ItemTemplate>
<asp:LinkButton ID="lnkFieldPermssion" Text="Set" runat="server" CommandName="cmdFieldPermission" />
</ItemTemplate>
</asp:TemplateColumn>
Javascript is:
function EnablePermissoin(chkB, cellNumber1, cellNumber2) {
var IsChecked = chkB.checked;
if (IsChecked) {
var cell1 = chkB.parentElement.parentElement.cells[cellNumber1];
for (i = 0; i < cell1.childNodes.length; i++) {
if (cell1.childNodes[i].tagName == "A") {
cell1.childNodes[i].disabled = false;
}
}
var cell2 = chkB.parentElement.parentElement.cells[cellNumber2];
for (i = 0; i < cell2.childNodes.length; i++) {
if (cell2.childNodes[i].tagName == "A") {
cell2.childNodes[i].disabled = false;
}
}
}
else {
var cell1 = chkB.parentElement.parentElement.cells[cellNumber1];
for (i = 0; i < cell1.childNodes.length; i++) {
if (cell1.childNodes[i].tagName == "A") {
cell1.childNodes[i].disabled = true;
}
}
var cell2 = chkB.parentElement.parentElement.cells[cellNumber2];
for (i = 0; i < cell2.childNodes.length; i++) {
if (cell2.childNodes[i].tagName == "A") {
cell2.childNodes[i].disabled = true;
}
}
}
}
This is the code obtained from view source of the browser, without disabling the link button on form loading:
<td align="center" style="font-weight:bold;">
<a id="DGDocuments_ctl23_lnkAddRules" href="javascript:WebForm_DoPostBackWithOptions(new WebForm_PostBackOptions("DGDocuments$ctl23$lnkAddRules", "", true, "", "", false, true))">Add Rules</a>
</td><td align="center" style="font-weight:bold;">
<a id="DGDocuments_ctl23_lnkFieldPermssion" href="javascript:WebForm_DoPostBackWithOptions(new WebForm_PostBackOptions("DGDocuments$ctl23$lnkFieldPermssion", "", true, "", "", false, true))">Set</a>
</td>
If I disable the link button on loading, this will be the code obtained from the view source:
<td align="center" style="font-weight:bold;">
<a id="DGDocuments_ctl23_lnkAddRules" disabled="disabled">Add Rules</a>
</td><td align="center" style="font-weight:bold;">
<a id="DGDocuments_ctl23_lnkFieldPermssion" disabled="disabled">Set</a>
</td>
Please help me to solve this. Thanks in advance.

It looks like when you disable the LinkButton server-side, it doesn't generate the onclick event handler for the a tag. So, once you enable the LinkButton through JavaScript, it doesn't know how to post back. I would suggest either rendering the LinkButton normally and then disabling it through JavaScript or setting AutoPostback to True for the checkbox and do the enabling server-side.

You are going to have to reconsider your solution. LinkButtons simply generate an <A> tag in the HTML. An <A> tag cannot be "disabled", so when you set a LinkButton to be Disabled, ASP.NET removes the HREF from the tag so that clicking it does nothing. I should point out that your JavaScript for disabling the <A> tag does not work - it makes the <A> tag look disabled, but it is still clickable.
For this to work client side, you will need your JavaScript function to add and remove the HREF from the <A> tag. Other options include doing everything server side, so that ASP.NET handles the removal and addition of the HREF, or switching to a different control, such as a regular asp:Button, which can be enabled and disabled.

Related

How to avoid page refresh in asp.net while click on link button the entire page is refreshing

Actually I used read more and hide two button for if data More than 40 character ,it's working fine but it's refreshing the page when click on button how to disable the refresh. In Asp.net
code in .aspx file
<asp:TemplateField HeaderText="UserdetailsDescription" ItemStyle-Width="50">
<ItemTemplate>
<asp:Label ID="lblDescription" runat="server"
Text='<%# Limit(Eval("UserdetailsDescription"),40) %>'
Tooltip='<%# Eval("UserdetailsDescription") %>'>
</asp:Label>
<asp:LinkButton ID="ReadMoreLinkButton" runat="server"
Text="Read More"
autopostback="false"
Visible='<%# SetVisibility(Eval("UserdetailsDescription"), 40) %>'
OnClick="ReadMoreLinkButton_Click">
</asp:LinkButton>
</ItemTemplate>
</asp:TemplateField>
##code Behind .CS file
## protected bool SetVisibility(object desc, int maxLength)
{
var description = (string)desc;
if (string.IsNullOrEmpty(description)) { return false; }
return description.Length > maxLength;
}
protected void ReadMoreLinkButton_Click(object sender, EventArgs e)
{
LinkButton button = (LinkButton)sender;
GridViewRow row = button.NamingContainer as GridViewRow;
Label descLabel = row.FindControl("lblDescription") as Label;
button.Text = (button.Text == "Read More") ? "Hide" : "Read More";
string temp = descLabel.Text;
descLabel.Text = descLabel.ToolTip;
descLabel.ToolTip = temp;
}
protected string Limit(object desc, int maxLength)
{
var description = (string)desc;
if (string.IsNullOrEmpty(description)) { return description; }
return description.Length <= maxLength ?
description : description.Substring(0, maxLength) + ".....";
}
I think UpdatePnael and PostBackTrigger can help you partially update the page without full postback. Adding Update Panel surrounding your link button and adding PostBackTrigger can help in your situation. For more details see this answer
There is no autopostback attribute on a linkbutton as far as I know.
Try a OnClientClick instead and make sure to return false from the function that you call there.
<asp:LinkButton ID="ReadMoreLinkButton" runat="server"
Text="Read More"
Visible='<%# SetVisibility(Eval("UserdetailsDescription"), 40) %>'
OnClientClick="HideReadMoreLinkButton(); return false"/>
<script>
function HideReadMoreLinkButton() {
//your code to hide button here
}
</script>
Note: if you get a page postback by another button the button will go back to visible because that is that state it is in kept in viewstate. So an option there is to have a hidden field maintain it's client state and a bit of JS on the page to restore the links back to hidden.
See also: Disable the postback on an <ASP:LinkButton>

Change text in button (gridview) using if else

I have one button to change based on the page. I have 3 page which is confirmed, pending and rejected.
On confirmed and rejected the text inside the button is same but different for pending. How can change the word in the button. The button placed in the grid view.
Below the code in aspx file:
<asp:TemplateField>
<HeaderTemplate>Actions</HeaderTemplate>
<ItemTemplate>
<asp:Button ID="lnkbtnInfo" runat="server" CssClass="btn btn-success" Text="" CommandArgument='<%# DataBinder.Eval(Container.DataItem, "Id") %>' CommandName="Detail" /></td>
</ItemTemplate>
</asp:TemplateField>
How can i do in the cs file, to use the if else.
For rejected and confirmed page, the button is "view" and pending page is "review"
I figured that you need to use RowDataBound event handler on gridview and create if statement based on button's CommandArgument state:
protected void GridView_RowDataBound(Object sender, GridViewRowEventArgs e)
{
for (int i = 0; i < GridView.Rows.Count - 1; i++)
{
Button status = (Button)GridView.Rows[i].FindControl("lnkbtnInfo"); // find control from your button ID
String state = status.CommandArgument.ToString(); // assume the value given by Eval data binding
if (state.Equals("confirmed") || state.Equals("rejected"))
{
status.Text = "view";
}
else // if (state.Equals("pending"))
{
status.Text = "review";
}
}
}
Reference: Change button text in asp:gridview based on cell value C#
What you can also do is use Eval with ternary for changing Button Text on .aspx page,
Ternary Operator syntax
(your condition) ? "if true value":" if false value";
Here is Example " if you want to check that your 'Id' is 3 then Button Text should be View else It should be Review."
<asp:Button ID="lnkbtnInfo" runat="server" CssClass="btn btn-success" Text='<%# ((int)Eval("Id") == 3) ? "view":"Review" %>' CommandArgument='<%# DataBinder.Eval(Container.DataItem, "Id") %>' CommandName="Detail" />
Here my answer that works on my situation:
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
for (int i = 0; i < GridView1.Rows.Count; i++)
{
Button name = (Button)GridView1.Rows[i].FindControl("lnkbtnInfo"); // find control from your button ID
Label status= (Label)GridView1.Rows[i].FindControl ("lblStatus");
if (status.Text == "Complete" || status.Text == "Rejected" || status.Text == "Cancelled" ||
status.Text == "Returned" || status.Text == "UserRejected")//refer to confirm and reject order
{
name.Text = "View";
}
else // refer to pending order
{
name.Text = "review";
}
}
}

Select All Checkbox feature in gridview not being implemented

I am having header in gridview that labels as "xls" and a checkbox, that when selected should select all the checkbox columns in gridview and unchecking the xls column should uncheck all the columns.
I am following two links:
Link-1
Here, the totalChkBoxes variable is coming null (despite my gridview has rows). In fact when debugging the JS, code inside parseInt and below line is coming as ''
Link-2
Here also the GridView2 variable is coming null.
One common change that i am doing in both the JS is replacing the <%=.....%> by <%#....%>
Please guide as to what i am doing wrong. You can also help by giving some suitable link to implement the desired functionality
CODE UPDATED WITH MY WORKING JS
<script type="text/javascript" language="javascript">
function checkAllBoxes() {
var gvControl = document.getElementById("gvSample");
//this is the checkbox in the item template.
var gvChkBoxControl = "chkSelectItem";
//Header Template checkbox.
var mainChkBox = document.getElementById("chkBoxAll");
//Array of Inputs in gridview.
var inputTypes = gvControl.getElementsByTagName("input");
for (var i = 0; i < inputTypes.length; i++) {
//if the input type is a checkbox and the id of it is what we set above
//then check or uncheck according to the main checkbox in the header template
if (inputTypes[i].type == 'checkbox' && inputTypes[i].id.indexOf(gvChkBoxControl, 0) >= 0)
inputTypes[i].checked = mainChkBox.checked;
}
}
GRIDVIEW CODE
<asp:TemplateField>
<HeaderTemplate>
<table style="width: 15px" cellpadding="0" cellspacing="0">
<tr>
<td>
<asp:Label ID="lblXls" runat="server" Text="xls"></asp:Label>
<br />
<input id="chkBoxAll" type="checkbox" onclick="checkAllBoxes()" />
</td>
</tr>
</table>
</HeaderTemplate>
<ItemTemplate>
<asp:CheckBox ID="chkSelectItem" runat="server" />
</ItemTemplate>
</asp:TemplateField>
Thanks!
Try changing your parseInt to something like this to see if it helps at all. I know it's only a small change, but small things tend to break JS code:
var totalChkBoxes = parseInt("<%=gvTest.Rows.Count%>");
Secondly, if you have runat="server" on the checkbox in the header, you may need to change this line if your JSFunction:
var mainChkBox = document.getElementById("<%=chkBoxAll.UniqueID%>");

How to access a Div inside a repeater using javascript

Simply, I have an anchor inside a repeater that triggers on click a javascript function, which sets the innerHTML of a Div to some content.
trying this outside a repeater did work!
but if I tried to implement the same code in the repeater's item template, it won't work!
NOTE: I think I need to access the repeater first then access the Anchor inside it! but I don't know how to do it
For further illustration:
JavaScript Function:
function show(ele, content) {
var srcElement = document.getElementById(ele);
if (srcElement != null) {
srcElement.innerHTML = content;
}
}
The repeater's code:
<asp:Repeater ID="Repeater1" runat="server" >
<ItemTemplate>
Name : <%# Eval("name")%>
<DIV ID= "PersonalInfo1" runat="server"></DIV>
<A id="A1" href="#" runat="server" onclick="show('PersonalInfo1','Address : ')">More...</A>
</ItemTemplate>
</asp:Repeater>
PS: THE POSTED CODE ISN'T WORKING IN THE REPEATER!
That is because id's are unique. Select elements using getElementsByName or by their class name with for example jQuery.
OK... let's start over.
Have such repeater code:
<asp:Repeater ID="Repeater1" runat="server" >
<ItemTemplate>
<div>
Name : <%# Eval("name")%>
<div id="Address" runat="server" style="display: none;"><%# Eval("address")%></div>
<div id="Interests" runat="server" style="display: none;"><%# Eval("interests")%></div>
<a id="A1" href="#" runat="server" onclick="return show(this, 'Address');">Show address</a>
<a id="A2" href="#" runat="server" onclick="return show(this, 'Interests');">Show interests</a>
</div>
</ItemTemplate>
</asp:Repeater>
Then such JavaScript code:
function show(oLink, targetDivID) {
var arrDIVs = oLink.parentNode.getElementsByTagName("div");
for (var i = 0; i < arrDIVs.length; i++) {
var oCurDiv = arrDIVs[i];
if (oCurDiv.id.indexOf(targetDivID) >= 0) {
var blnHidden = (oCurDiv.style.display == "none");
oCurDiv.style.display = (blnHidden) ? "block" : "none";
//oLink.innerHTML = (blnHidden) ? "Less..." : "More...";
}
}
return false;
}
This will search for "brother" DIV element of the clicked link, and show or hide it.
The code is as simple as possible using pure JavaScript, you should be able to understand what each line is doing - feel free to ask if you don't. :)
Note, you have to put the personal info in the PersonalInfo div in advance instead of passing it to the function - the function will get pointer to the clicked link.
Yes you need to iterate all the relevant links. Solution that involve minimal change of code is adding class to the links then check for this class:
<A id="A1" href="#" runat="server" class="RepeaterLink" ...>
And then in JavaScript:
var arrLinks = document.getElementsByTagName("a");
for (var i = 0; i < arrLinks.length; i++) {
var oLink = arrLinks[i];
if (oLink.className == "RepeaterLink") {
//found link inside repeater..
oLink.click();
}
}
This will "auto click" all the links, you can check ID or something else to imitate click of specific link in the repeater as well.

how to check status of checkboxes in gridview columns on click of button

T have used checkbox column in gridview. On click of a linkbutton, it should be checked that checkboxes in gridview are checked or not. If none check box is checked then it should display alert("Check at leat one check box").
You will have to add some custom Javascript to your page for the client-side alert to show. Here's a method that I've written that works with a GridView called 'GridView1' (this should be the default name if you've just dragged the control onto your ASPX page):
<script type="text/javascript">
function ClientCheck() {
var valid = false;
var gv = document.getElementById("GridView1");
for (var i = 0; i < gv.all.length; i++) {
var node = gv.all[i];
if (node != null && node.type == "checkbox" && node.checked) {
valid = true;
break;
}
}
if (!valid) {
alert("Invalid. Please select a checkbox to continue.");
}
return valid;
}
</script>
You can see that it sets a variable to the GridView control to start with, then iterates through all the children in a for loop. If the child is a checkbox and it is checked, then we set the valid variable to true. If we get to the end of the iteration and no checked checkboxes are found, then valid remains false and we execute the alert.
To link this into your GridView on your ASPX page, first make the button column a TemplateField and surround the LinkButton with your client-side code. If you've used the designer to set up your columns, you can use the "Convert this field into a TemplateField" link in the column editor). Here's an example of the source you'll end up with:
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" DataSourceID="ObjectDataSource1">
<Columns>
<asp:TemplateField HeaderText="Button Field" ShowHeader="False">
<ItemTemplate>
<span onclick="return ClientCheck();">
<asp:LinkButton ID="LinkButton1" runat="server" CommandName="IDClick" Text='<%# Eval("YourDataSourceItem") %>'></asp:LinkButton>
</span>
</ItemTemplate>
</asp:TemplateField>
// ...your remaining columns...
Using the TemplateField lets us add any client-side code we like. Here we're adding a span and using onclick to call our ClientCheck method.
If you aren't bothered about the alert, you could achieve your aims by using a CustomValidator control, which executes on the server-side.
I hope this helps.
I found the answer. and its working...
function checkBoxselectedornot()
{
var frm=document.forms['aspnetForm'];
var flag=false;
for(var i=0;i<document.forms[0].length;i++)
{
if(document.forms[0].elements[i].id.indexOf('chkDownloadSelectedEvent')!=-1)
{
if(document.forms[0].elements[i].checked)
{
flag=true
}
}
}
if (flag==true)
{
return true
}else
{
alert('Please select at least one Event.')
return false
}
}
and girdview code is...
<asp:BoundField ItemStyle-Width ="100px" DataField ="EventStartDate" DataFormatString ="{0:g}" HeaderText ="<%$ Resources:stringsRes, ctl_EventList_StartDate %>" SortExpression ="EventStartDate" HtmlEncode ="true" ItemStyle-Wrap ="false" />
<asp:BoundField ItemStyle-Width="100px" DataField="EventDate" DataFormatString="{0:g}" HeaderText="<%$ Resources:stringsRes, ctl_EventList_Date %>" SortExpression="EventDate" HtmlEncode="true" ItemStyle-Wrap="false" />
<asp:ButtonField ItemStyle-Width="150px" ButtonType="Link" DataTextField="EventName" HeaderText="<%$ Resources:stringsRes, ctl_EventList_Event %>" SortExpression="EventName" CommandName="show_details" CausesValidation="false" />
<asp:BoundField DataField="EventLocation" HeaderText="<%$ Resources:stringsRes, ctl_EventList_Location %>" SortExpression="EventLocation" />
<asp:TemplateField HeaderText ="Select">
<ItemTemplate >
<asp:CheckBox ID="chkDownloadSelectedEvent" runat ="server" AutoPostBack ="false" Onclick="eachCheck();"/>
</ItemTemplate>
</asp:TemplateField>
</Columns>
<RowStyle Height="25px" />
<HeaderStyle Height="30px"/>
</asp:GridView>
and there is a link button ....
I havnt used the checkbox in grid view but would you not do a for loop around the columns in gridview and check the state? Myabe add a count and if 0 then alert.
var grid = document.getElementById("gridId"); //Retrieve the grid
var inputs = grid.getElementsByTagName("input"); //Retrieve all the input elements from the grid
var isValid = false;
for (var i=0; i < inputs.length; i += 1) { //Iterate over every input element retrieved
if (inputs[i].type === "checkbox") { //If the current element's type is checkbox, then it is wat we need
if(inputs[i].checked === true) { //If the current checkbox is true, then atleast one checkbox is ticked, so break the loop
isValid = true;
break;
}
}
}
if(!isValid) {
alert('Check at least one checkbox');
}

Categories