Hi I am developing one application. I have one multiselect dropdownlist box. Whenever i select one value in dropdownlistbox corresponding value in gridview will be having checkbox in below gridview. I want to disable that checkbox. I am basically mvc developer and finding hard times to fix this. I am trying my level best to fix this. For example, whever i select some value in dropdown I am getting ID using jquery as below.
<script>
$(function() {
$('.limitedNumbSelect2').change(function (e) {
var selected = $(e.target).val();
});
});
This is my gridview.
<asp:GridView ID="gdvRegretletter" CssClass="tableform" runat="server" AutoGenerateColumns="False" DataKeyNames="Vendor_ID"
EmptyDataText="No records found !" ShowHeaderWhenEmpty="true" AllowPaging="true" OnPageIndexChanging="gdvRegretletter_PageIndexChanging">
<Columns>
<asp:TemplateField ShowHeader="true" HeaderText="Select All">
<HeaderTemplate>
<asp:CheckBox ID="checkAll" runat="server" Text="Check All" onclick="checkAll(this);" />
</HeaderTemplate>
<ItemTemplate>
<asp:CheckBox ID="chkselect" runat="server" onclick="Check_Click(this)" />
<asp:HiddenField ID="id" runat="server" Value='<%#Eval("Vendor_ID")%>' />
</ItemTemplate>
<HeaderStyle Width="8%" />
<ItemStyle VerticalAlign="Top" Width="8%" />
</asp:TemplateField>
<asp:TemplateField HeaderText="Username">
<ItemTemplate>
<asp:Label ID="lblUsername" runat="server" Text='<%#Eval("Username") %>' />
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Name">
<ItemTemplate>
<asp:Label ID="lblName" runat="server" Text='<%#Eval("Name") %>' />
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Email Id">
<ItemTemplate>
<asp:Label ID="lblEmail" runat="server" Text='<%#Eval("Email") %>' />
</ItemTemplate>
</asp:TemplateField>
</asp:GridView>
Whenecer i select some value from multiselect dropdownlist box I get id in a variable selected. As soon as I get ID in a variable selected i want to disable that checkbox in gridview. May i have some suggestions on this! Thank you all
Furthur i tried as below.
This is jquery code to hide checkbox
$('.limitedNumbSelect2').change(function (e) {
selected = $(e.target).val();
`$(".disablechk[Text='selected']").prop("disabled", true);`
This is my checkbox code inside gridview.
<asp:CheckBox ID="chkselect" runat="server" onclick="Check_Click(this)" Text='<%#Eval("Vendor_ID")%>' class="disablechk"/>
I am trying to do whenever i get some value from dropdown slected i want to disable that particular checkbox.
If you are getting comma separated string then split it and make an array
var temp = new Array();
temp = selected.split(",");
then loop through it
$.each(temp, function( index, value ) {
$(".disablechk[Text='" + value + "']").prop("disabled", true);
});
You can loop the GridView HiddenField values and disable the checkbox accordingly.
<script type="text/javascript">
$(function() {
$('.limitedNumbSelect2').change(function (e) {
checkGridView($(e.target).val());
});
});
function checkGridView(selected) {
$('#<%= gdvRegretletter.ClientID %> input[type="hidden"]').each(function () {
if ($(this).val() == selected) {
var checkbox = $(this).prev();
checkbox.prop("disabled", true);
}
});
}
</script>
Related
I have GridView and a button as follows. Then i am binding the gridview with data from my database. GridView has two hiddenfield for Id and ClassIndex.
when i selecting a checkbox and click button, i want to get the corresponding Id and FileName.
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False">
<Columns>
<asp:TemplateField>
<ItemTemplate>
<asp:CheckBox ID="check" runat="server" />
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField>
<ItemTemplate>
<asp:HiddenField ID="hdfId" runat ="server" Value='<%#Eval("Id") %>' />
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField>
<ItemTemplate>
<asp:HiddenField ID="hdfClssIndex" runat ="server" Value='<%#Eval("ClassIndex") %>' />
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField>
<ItemTemplate>
<asp:Label ID="lblFileName" runat ="server" Text='<%#Eval("FileName") %>' />
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
and Button Like
<asp:Button ID="Button1" runat="server" onclick="Button1_Click"
Text="Send Request" />
the code behind button is
protected void Button1_Click(object sender, EventArgs e)
{
foreach (GridViewRow row in GridView1.Rows)
{
var check = row.FindControl("check") as CheckBox;
if (check.Checked)
{
int Id = Convert.ToInt32(row.Cells[1].Text);
//some logic follws here
}
}
}
but i am getting an error like
Input string was not in a correct format.
What is the error and how to solve it?
Your looping correct.
But you forgot to notice one thing here, when you wanted to access CheckBox you did a FindControl on row. Which means you are trying to find some control in that row.
Then why are you accessing HiddenField control inside row with row.Cell[1].Text?
Try to find that also.
int Id = Convert.ToInt32(((HiddenField)row.FindControl("hdfId")).Value);
I am working on creating a nested gridview. I am using an example from: http://www.aspsnippets.com/Articles/ASPNet-Nested-GridViews-GridView-inside-GridView-with-Expand-and-Collapse-feature.aspx
The problem is the "minus" of the script does not remove the nested gridview. What seems to be happen is the "plus" function seems to trigger again and again.
<script type = "text/javascript">
$(document).ready(function () {
$("[src*=plus]").on("click", function () {
$(this).closest("tr").after("<tr><td></td><td colspan = '999'>" + $(this).next().html() + "</td></tr>")
$(this).attr("src", "images/minus.png");
});
$("[src*=minus]").on("click", function () {
$(this).attr("src", "images/plus.png");
$(this).closest("tr").next().remove();
});
});
I am using an UpdatePanel (The 2 gridviews are Inside).
<asp:UpdatePanel ID="UpdatePanel1" runat="server">
<ContentTemplate>
<script type="text/javascript">
Sys.Application.add_load(BindEvents);
</script>
<asp:GridView ID="GridView1" runat="server" Width = "100%" AutoGenerateColumns = "False" Font-Names = "Arial" CssClass="table table-hover table-bordered"
Font-Size = "11pt" AlternatingRowStyle-BackColor = "#F18903" HeaderStyle-BackColor = "#F18A07" AllowPaging ="True"
DataKeyNames="Rut" OnPageIndexChanging = "OnPaging" onrowediting="EditCustomer" OnRowDataBound="OnRowDataBound" onrowupdating="UpdateCustomer" onrowcancelingedit="CancelEdit" >
<Columns>
<asp:TemplateField>
<ItemTemplate>
<img alt = "" style="cursor: pointer" src="images/plus.png" />
<asp:Panel ID="pnlOrders" runat="server" Style="display: none">
<asp:GridView ID="gvOrders" runat="server" AutoGenerateColumns="false" CssClass = "ChildGrid">
<Columns>
<asp:BoundField ItemStyle-Width="150px" DataField="Nombre" HeaderText="Order Id" />
<asp:BoundField ItemStyle-Width="150px" DataField="Rut" HeaderText="Date" />
</Columns>
</asp:GridView>
</asp:Panel>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText = "Nombre" >
<ItemTemplate>
<asp:Label ID="lblNombre" runat="server" Text='<%# Eval("Nombre")%>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText = "Rut">
<ItemTemplate >
<asp:Label ID="lblRut" DataField="Rut" runat="server" Text='<%# Eval("Rut")%>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText = "Fecha de Nacimiento">
<ItemTemplate>
<asp:Label ID="lblFecha_Nac" runat="server" Text='<%# Eval("Fecha_Nac")%>'></asp:Label>
</ItemTemplate>
<EditItemTemplate>
<div class='input-group date' id='datetimepicker1'>
<asp:TextBox ID="txtFecha_Nac" runat="server" Text='<%# Eval("Fecha_Nac")%>'></asp:TextBox>
<span class="input-group-addon"><span class="glyphicon glyphicon-calendar"></span></span>
</div>
</EditItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText = "Celular">
<ItemTemplate>
<asp:Label ID="lblCelular" runat="server" Text='<%# Eval("Celular")%>'></asp:Label>
</ItemTemplate>
<EditItemTemplate>
<asp:DropDownList ID="txtCelular" runat="server" >
<asp:ListItem Text="SI" Value="1" />
<asp:ListItem Text="NO" Value="0" />
</asp:DropDownList>
</EditItemTemplate>
</asp:TemplateField>
<asp:CommandField EditText="Editar" ShowEditButton="True" />
<asp:TemplateField HeaderText="Informacion Adicional" >
<ItemTemplate>
<asp:Button ID="Btn1" runat="server"
Text="Ver Mas" CommandArgument="Button1"
OnClick="Btn1_Click"/>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Cambio Final" >
<ItemTemplate>
<asp:Button ID="BtnCambio" runat="server"
Text="Check" CommandArgument="Button1"
OnClick="Btn1_ClickCambioFinal"/>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Image">
<EditItemTemplate>
<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
</EditItemTemplate>
<ItemTemplate>
<asp:Image ID="Image1" runat="server" />
</ItemTemplate>
</asp:TemplateField>
</Columns>
<AlternatingRowStyle BackColor="#FBEDBB" />
<HeaderStyle BackColor="#F18A07" />
</asp:GridView>
</ContentTemplate>
<Triggers>
<asp:AsyncPostBackTrigger ControlID = "GridView1" />
</Triggers>
</asp:UpdatePanel>
This is an issue with what event is bound when the document is ready.
If you want to "toggle" between two function calls, there are many addon that can help you with that (see this SO question).
An easy way to implement it would be to use jquery one function as mentionned by Tushar Gupta.
function plus() {
$(this).closest("tr").after("<tr><td></td><td colspan = '999'>" + $(this).next().html() + "</td></tr>");
$(this).attr("src", "images/minus.png");
$(this).one("click", minus);
}
function minus() {
$(this).attr("src", "images/plus.png");
$(this).closest("tr").next().remove();
$(this).one("click", plus);
}
$(document).ready(function(){
$("[src*=plus]").one("click", plus);
//You might want to change the selector with a class
// to your img so you don't have to worry about
// opened or closed by default
});
Hope this helps!
Explanations :
The on function bind the event to the DOM element when it is called. In your case, when the document is ready.
When the document is loaded, all your table lines are showing the expand image. Therefore, the "plus click" function is bound to all the img tags.
On the other hand, there are no element showing the minus sign (yet). So no "minus click" function is bound.
The on function doesn't care if you change your element attributes. Remember that your selector selects the elements, even though you filter through the attribute.
In the link you provided, the author used the live function. This function is now deprecated, but it was basically a on function, that would work on the selector now and in the future. This is not the case anymore with the on function.
I would assume that you need to re-subscribe to the events. JavaScript is executed top-down which means that after you have subscribed to the event, elements created later will not trigger that event.
Like the following example:
function myEventHandler () {
// In here you perform your event-specific code
eventSubscription();
}
var eventSubscription = function () {
// Make sure to unsubscribe to prevent event to fire multiple times
$('.myClass').unbind('click');
// Re-subscribe to event
$('.myClass').on('click', myEventHandler);
}
// Call the eventSubscription to hook your events
eventSubscription();
As noMad17 said, you need to re-subscribe to your js methods after a postback, even though you're using an updatePanel. Here is my code:
//js file:
$(document).ready(function () {
loadConfiguration();
});
function loadConfiguration()
{
//add your configuration here
}
//aspx file
<asp:UpdatePanel runat="server" ID="upnl1" UpdateMode="Conditional" >
<ContentTemplate>
<script type="text/javascript">
Sys.Application.add_load(loadConfiguration);
</script>
<!--More code here...-->
</asp:UpdatePanel>
After postback, UpdatePanel is build and all the content inside it as well, so it will load the js code inside add_load again.
Hope it helps
In the below code i have gridview which has textbox and dropdownlist i want to add rows using javascript.My aim is to avoid postback on adding rows.
Markup code:
<asp:GridView runat="server" ID="gvProduct" AutoGenerateColumns="false"
Width="100%" CellPadding="4" ForeColor="#333333" ShowFooter="true"
PageSize-Mode="NumericPages" PagerStyle-Visible="true" AllowPaging="false" AllowSorting="true"
CssClass="mGrid" PagerStyle-CssClass="pgr" AlternatingRowStyle-CssClass="alt"
OnRowDataBound="gvProduct_RowDataBound" OnRowCommand="gvProduct_RowCommand" OnRowDeleting="gvProduct_RowDeleting">
<Columns>
<asp:TemplateField HeaderText="Product Name" ItemStyle-Width="350px">
<ItemTemplate>
<asp:DropDownList ID="ddlProduct" runat="server" AutoPostBack="false" Style="width: 100%; height:23px" ></asp:DropDownList>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Current Stock" ItemStyle-Width="80px" Visible="false">
<ItemTemplate>
<asp:Label ID="lblCurrentStock" runat="server" onkeypress="return isNumberKey(event, false);" Height="20px" style="width:80px" Enabled="false" ></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Quantity" ItemStyle-Width="80px">
<ItemTemplate>
<asp:TextBox ID="txtQuantity" onkeypress="return isNumberKey(event, false);" runat="server" Height="20px" Width="150px" onblur="js_function(this);" > </asp:TextBox>
<asp:Label ID="lblunittype" runat="server" ></asp:Label>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
<asp:Button ID="Button2" OnClientClick="AddRow(); return false;" runat="server" Text="Button" />
Javascript code:
function AddRow() {
var table = document.getElementById('<%=gvProduct.ClientID %>');
var newRow = table.insertRow();
var i = 0;
for (i = 0; i < table.rows[0].cells.length; i++) {
var newCell = newRow.insertCell();
newCell.innerHTML = 'New Row';
}
}
Gridview in asp = Table in HTML
new row in Gridview in asp = new row in Table in HTML
Sample JavaScript code:
function AddRow() {
let tableRef = document.getElementById('MainContent_gvItems');
let newRow = tableRef.insertRow(-1);//inserts at last row
let Cell0 = newRow.insertCell(0);
let Text0 = document.createTextNode('mydata');
Cell0.appendChild(Text0);
}
Btw, GridView must be visible even it's empty.
If you just want to add rows to the table for presentation, then #Mostafa Shehata answer should work fine.
However adding rows in JavaScript does not attached it to the GridView datasource. Therefore you'll experience issues with processing the data in the backend (such as saving to database).
Two possible solutions:
Replace GridView with a html table. The data can be populated & updated using a JavaScript calls to a restful API.
Pre-populate the GridView datasource with empty rows.
Data-bind x amount of empty fields (for example 10 empty fields).
In the GridView markup hide all the rows using css.
Run JavaScript to show rows that are not empty.
The “add row” button can just show the first empty row.
Add some sort of notification, if all empty fields have been used. (for example: "please save your data, before continuing").
In code behind, remove all empty fields before consuming it.
I have a gridview with two check box columns. One is for selection and the other for setting a property something like "add to favorite". This gridview is loaded code behind and the check boxes are defined inside Item Template. The problem is that it is not very user friendly to have someone check two boxes for the same row, when they could have just selected "add to favorite" and this should automatically check the selection check box too. I understand this could be easily done using jquery as I do not think making a postback for these selections is a good user experience. I am very new to jquery and so any help would be appreciated.
The checkboxes on the same row follow the same convention for id, so if select is cbSelect_0, the other one will be cbfavorite_0. I also gave all the cbFavorite checkboxes the same class "cbMul" and then I wrote a function
function checkUncheck() {
$(".cbMul").checked(function() {
if ( $(this).attr('checked')) {
$('#myCheckbox').attr('checked', false);
} else {
$('#myCheckbox').attr('checked', 'checked');
}
});
}
Now, I do not understand how do I get the attributes of the checkbox that was checked, replace the the name and get the id of the checkbox if select and then check that one?
Here is the gridview:
<asp:GridView ID="gvEnvironments" EmptyDataText="--- No Data ---" runat="server" AutoGenerateColumns="false"
DataKeyNames="Id" >
<Columns>
<asp:TemplateField HeaderText="Select">
<ItemTemplate>
<asp:CheckBox ID="cbSelectEnvironments" runat="server" />
</ItemTemplate>
</asp:TemplateField>
<asp:BoundField DataField="Id" HeaderText="ID" InsertVisible="false" ReadOnly="true" SortExpression="Id" />
<asp:TemplateField HeaderText="Multi">
<ItemTemplate>
<asp:CheckBox ID="cbFav" runat="server" Checked="false" CssClass="cbMul" />
</ItemTemplate>
</asp:TemplateField>
<asp:BoundField DataField="Name" HeaderText="Name" SortExpression="Name" />
<asp:BoundField DataField="Description" HeaderText="Description" HeaderStyle-Width="300px" SortExpression="Description" />
</Columns>
Here is a fiddle: http://jsfiddle.net/FyDEk/
HTML:
<table>
<tr>
<td>
<input class="cb1" type="checkbox" />
</td>
<td>
<div id="dd">text</div>
</td>
<td>
<input class="cb2" type="checkbox" />
</td>
</tr>
</table>
JS:
$(function () {
$(".cb2").on("change", function () {
var cb = $(this),
cbIsChecked = cb.is(":checked"),
cbPrev = cb.parent().parent().find(".cb1");
if(cbIsChecked)
cbPrev.prop("checked", true);
else
cbPrev.prop("checked", false);
});
});
Add appropriate classes to your CheckBoxes.
I create gridview and remove the select button to make all row clickable but I want to redirect the user for selected item detail
Note: I remover the CommandField select Visible="False"
int rowCount = 0;
protected void gv_TasksProjectForUser_RowCreated(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
//var taskID = gv_TasksProjectForUser.SelectedDataKey.Value;
e.Row.Attributes.Add("onclick", "location='TaskDetail.aspx?taskID=" + e.Row.RowIndex + "'");
e.Row.Attributes.Add("onmouseover", "JavaScript:this.style.cursor='pointer';");
}
rowCount++;
}
I have made this with Item Templates.
What you have to do is remove the property AutogenerateColums and add them manually with objects and item templates, on those add one that could be a button.
Later on the code Behind add a event to handle the button click, on that event you can do the response.redirect to another page.
<asp:GridView ID="userGrid" runat="server" CssClass="AdminGrid"
AllowPaging="True" AutoGenerateColumns="False" PageSize="11">
<Columns>
<asp:BoundField DataField="ApplicationId" Visible="False" />
<asp:BoundField DataField="UserName" Visible="False" />
<asp:TemplateField >
<HeaderTemplate>
<asp:Label ID="lblEmail" Text="E-Mail" runat="server" CssClass = "HeaderLabel" meta:resourcekey="lblEmail"></asp:Label>
<asp:ImageButton ID="imgSortEMail" runat="server" ImageUrl="~/Images/normal.gif" OnClick="SortGrid" CommandArgument="EMail" CssClass="SortButton" ToolTip="Click here to Order" />
</HeaderTemplate>
<ItemTemplate>
<asp:HyperLink ID="lnkEMail" runat="server" CssClass="EmailLinkButton" Text='<%# FormatGridTextDisplay(DataBinder.Eval(Container.DataItem, "EMail")) %>' ToolTip='<%# DataBinder.Eval(Container.DataItem, "EMail") %>' NavigateUrl='<%# DataBinder.Eval(Container.DataItem, "EMail","mailto:{0}") %>' ></asp:HyperLink>
</ItemTemplate>
<HeaderStyle CssClass="OverFlowStringField" />
<ItemStyle CssClass="OverFlowLeftAligned" />
</asp:TemplateField>
<asp:TemplateField >
<HeaderTemplate>
<asp:Label ID="lblSalonUser" Text="Salon User" runat="server" CssClass = "HeaderLabel" meta:resourcekey="lblSalonUser"></asp:Label>
<asp:ImageButton ID="imgSortIsSalonUser" runat="server" ImageUrl="~/Images/normal.gif" OnClick="SortGrid" CommandArgument="IsSalonUser" CssClass="SortButton" ToolTip="Click here to Order" />
</HeaderTemplate>
<ItemTemplate>
<asp:CheckBox ID="chkSalonUser" runat="server" Checked='<%# DataBinder.Eval(Container.DataItem, "IsSalonUser") %>' onclick="javascript:if (this.checked==true) this.checked=false; else this.checked=true;"/>
</ItemTemplate>
<HeaderStyle CssClass="OverFlowStringField" />
<ItemStyle CssClass="CenterAligned" />
</asp:TemplateField>
<asp:TemplateField >
<ItemTemplate>
<asp:Button ID="btnEdit" runat="server" Text="Editar" CssClass="GridButton" CommandArgument='<%# DataBinder.Eval(Container.DataItem, "UserName")%> ' OnClick="btnEdit_Click" meta:resourcekey="btnEdit"/>
</ItemTemplate>
<HeaderStyle CssClass="OverFlowStringField" />
<ItemStyle CssClass="CenterAligned" />
</asp:TemplateField>
</Columns>
</asp:GridView>
There You can see that i add a few types of items template, the most important is the btnEdit, on that one there are 2 important properies, one is the CommandArgument where you send the values to redirect to the page and the other is the event OnClick that is the one that will handle the click for the button.
Protected void btnEdit_Click(Object sender , System.EventArgs e ){
Button clickedButton = (sender)Button;
String() argumentsSend = clickedButton.CommandArgument.ToString().Split("|");
String backParameters;
Response.Redirect(String.Concat("RedirectPage.aspx?user=", Server.UrlEncode(argumentsSend(0)), "&company=", Server.UrlEncode(argumentsSend(1)), True);
}
I took this code from VB and change it to c# with a compiler, it may have errors, but that's the idea.
A easyest way is to use a link button or an hipperlink on the template of the grid, that eay you may no need to go to the code file.