I have a asp.net grid view which has a buttonfield to reset a user? I need to call a js function to get a confirmation message, when the buttonfield clicks, Any ideas? TIA
here is my grid view
<asp:GridView ID="grdAllProducts" runat="server" AutoGenerateColumns="False" CellPadding="4" ForeColor="#333333" GridLines="None" Width="100%" OnRowCommand="grdAllProducts_RowCommand">
<AlternatingRowStyle BackColor="White" />
<Columns>
<asp:BoundField DataField="USER_ID" HeaderText="User ID" />
<asp:BoundField DataField="USER_NAME" HeaderText="User Name" />
<asp:BoundField DataField="EMAIL" HeaderText="E-mail" />
<asp:BoundField DataField="PHONE_NUMBER" HeaderText="Phone No." />
<asp:BoundField DataField="USER_ROLE_NAME" HeaderText="User Role" />
<asp:ButtonField ButtonType="Button" Text="Reset" />
</Columns>
<EditRowStyle BackColor="#7C6F57" />
<FooterStyle BackColor="#1C5E55" Font-Bold="True" ForeColor="White" />
<HeaderStyle BackColor="#1C5E55" Font-Bold="True" ForeColor="White" />
<PagerStyle BackColor="#666666" ForeColor="White" HorizontalAlign="Center" />
<RowStyle BackColor="#E3EAEB" />
<SelectedRowStyle BackColor="#C5BBAF" Font-Bold="True" ForeColor="#333333" />
<SortedAscendingCellStyle BackColor="#F8FAFA" />
<SortedAscendingHeaderStyle BackColor="#246B61" />
<SortedDescendingCellStyle BackColor="#D4DFE1" />
<SortedDescendingHeaderStyle BackColor="#15524A" />
</asp:GridView>
here is my js function
function validateResetButton() {
if (confirm('Are you sure you want to Reset this User?')) {
return true;
}
else {
return false;
}
}
This works for me...
Add commandname in buttonfield
<asp:ButtonField ButtonType="Button" Text="Reset" CommandName="Reset" />
Add rowdatabound to gridview control
protected void grdAllProducts_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
// if you dont want the for loop directly put the button index
for (int i = 0; i < e.Row.Cells.Count; i++)
{
foreach (Button button in e.Row.Cells[i].Controls.OfType<Button>())
{
if (button.CommandName == "Reset")
{
button.Attributes["onclick"] = "if(!confirm('Do you want to Reset ?')){ return false; };";
}
}
}
}
}
in most cases, it MUCH easer to just drop in a regular plain jane button.
So, say we have this simple GV.
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="false"
CssClass="table table-hover table-striped" Width="50%"
DataKeyNames="ID">
<Columns>
<asp:BoundField DataField="FirstName" HeaderText="FirstName" />
<asp:BoundField DataField="LastName" HeaderText="LastName" />
<asp:BoundField DataField="City" HeaderText="City" />
<asp:BoundField DataField="HotelName" HeaderText="HotelName" />
<asp:BoundField DataField="Description" HeaderText="Description" />
<asp:TemplateField ItemStyle-HorizontalAlign="Center">
<ItemTemplate>
<asp:Button ID="cmdDel" runat="server" Text="Delete" CssClass="btn" />
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
And code to load:
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
LoadGrid();
}
void LoadGrid()
{
using (SqlConnection conn = new SqlConnection(Properties.Settings.Default.TEST4))
{
string strSQL = "SELECT * FROM tblHotelsA ORDER BY HotelName";
using (SqlCommand cmdSQL = new SqlCommand(strSQL, conn))
{
DataTable rstData = new DataTable();
conn.Open();
rstData.Load(cmdSQL.ExecuteReader());
GridView1.DataSource = rstData;
GridView1.DataBind();
}
}
}
And we now have this:
So, lets now add a click event to the button.
so, we have now this:
<asp:TemplateField ItemStyle-HorizontalAlign="Center">
<ItemTemplate>
<asp:Button ID="cmdDel" runat="server"
Text="Delete"
CssClass="btn"
onclick="cmdDel_Click"
onclientClick="return confirm('really delete this?');"
/>
</ItemTemplate>
</asp:TemplateField>
And our code behind click event?
Say this:
protected void cmdDel_Click(object sender, EventArgs e)
{
Button btnDel = (Button)sender;
GridViewRow gRow = (GridViewRow)btnDel.NamingContainer;
// get PK id of row
// (note how this is hidden - NEVER exposed client side
int PKID = (int)GridView1.DataKeys[gRow.RowIndex]["ID"];
Debug.Print("Row index click = " + gRow.RowIndex);
Debug.Print("pk row id for click = " + PKID);
string strSQL = "DELETE FROM tblHotelsA WHERE ID = #ID";
using (SqlConnection conn = new SqlConnection(Properties.Settings.Default.TEST4))
{
using (SqlCommand cmdSQL = new SqlCommand(strSQL, conn))
{
conn.Open();
cmdSQL.Parameters.Add("#ID", SqlDbType.Int).Value = PKID;
cmdSQL.ExecuteNonQuery();
}
}
}
Related
I want to get the div with id forExport and the Hidden Field Value
<table width="100%">
<tr>
<td>
<asp:HiddenField ID="hidGridView" runat="server"/>
<asp:GridView ID="grvPayroll" CssClass="table table-striped table-bordered table-hover"
AllowPaging="true"
runat="server" AutoGenerateColumns="False" DataKeyNames="Id"
OnRowCancelingEdit="grvPayroll_RowCancelingEdit" OnRowDataBound="grvPayroll_RowDataBound"
OnRowEditing="grvPayroll_RowEditing" OnRowUpdating="grvPayroll_RowUpdating"
OnRowCommand="grvPayroll_RowCommand" ShowFooter="True" OnRowDeleting="grvPayroll_RowDeleting"
OnRowDeleted="grvPayroll_RowDeleted" OnRowUpdated="grvPayroll_RowUpdated"
OnPageIndexChanging="grvPayroll_OnPageIndexChanging" PageSize="5" OnRowCreated="grvPayroll_RowCreated">
<Columns >
<asp:TemplateField>
<ItemTemplate>
<a href="javascript:expandcollapse('div<%# Eval("Id") %>', 'one');">
<img id='imgdiv<%# Eval("Id") %>' alt="Click to show/hide Payroll Details <%# Eval("PayrollCode") %>" border="0" src="../App_Themes/Admin/img/plus.png"/>
</a>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="PayrollCode" SortExpression="PayrollCode">
<EditItemTemplate>
<asp:TextBox ID="txtPayrollCode" runat="server" Text='<%# Eval("PayrollCode") %>' CssClass="textbox"></asp:TextBox>
<asp:RequiredFieldValidator ID="rfvtxtPayrollCode"
runat="server" ControlToValidate="txtPayrollCode"
ErrorMessage="Required">
*
</asp:RequiredFieldValidator>
</EditItemTemplate>
<FooterTemplate>
<asp:TextBox ID="txtNewPayrollCode" runat="server" CssClass="textbox"></asp:TextBox>
</FooterTemplate>
<ItemTemplate>
<asp:Label ID="lblPayrollCode" runat="server" Text='<%# Bind("PayrollCode") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Function" ShowHeader="False">
<EditItemTemplate>
<asp:LinkButton ID="lbtUpdate" runat="server" CausesValidation="False" CommandName="Update" Text="Update"></asp:LinkButton>
<asp:LinkButton ID="lbtCancel" runat="server" CausesValidation="False" CommandName="Cancel" Text="Cancel"></asp:LinkButton>
</EditItemTemplate>
<FooterTemplate>
<asp:ImageButton ID="lbtAddNew" runat="server" ToolTip="Add New" ImageUrl="../App_Themes/Admin/img/file_add.png" CausesValidation="False" CommandName="AddNew"/>
</FooterTemplate>
<ItemTemplate>
<asp:ImageButton ID="lbtEdit" runat="server" ToolTip="Edit" ImageUrl="../App_Themes/Admin/img/edit.png" CausesValidation="False" CommandName="Edit"/>
<asp:ImageButton ID="lbtDelete" runat="server" ToolTip="Delete" ImageUrl="../App_Themes/Admin/img/delete.png" OnClientClick=" return confirm('Are you sure you want to delete this?'); " CausesValidation="False" CommandName="Delete"/>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField>
<ItemTemplate>
<tr>
<td colspan="100%">
<div id='div<%# Eval("Id") %>' style="display: none; left: 15px; OVERFLOW: auto; position: relative; WIDTH: 98%">
<div id="forExport">
<asp:GridView ID="grvPayrollDetails"
EmptyDataText="No Records Found" CellPadding="5" ForeColor="#333333" GridLines="Both" AllowPaging="False"
runat="server" AutoGenerateColumns="False" DataKeyNames="PayrollID"
OnRowDataBound="grvPayrollDetails_RowDataBound" OnRowCreated="grvPayrollDetails_RowCreated">
<AlternatingRowStyle CssClass="GridStyle_AltRowStyle2"/>
<HeaderStyle CssClass="GridStyle_HeaderStyle2"/>
<RowStyle CssClass="GridStyle_RowStyle2"/>
<Columns >
<asp:TemplateField HeaderText="Mã NV">
<ItemTemplate>
<asp:Label ID="plEmpID" runat="server" Visible="false" Text='<%# Eval("EmpID").ToString() %>'></asp:Label>
<%#get_EmpCode(Eval("EmpID").ToString()) %><br/>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Tổng chi phí">
<ItemTemplate>
<asp:Label ID="lblTotalPaymentCost" runat="server" Text='<%#Format_Money(Eval("TotalPaymentCost").ToString()) %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
</div>
</div>
</td>
</tr>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
</td>
</tr>
</table>
And this is the script:
<script type="text/javascript">
function expandcollapse(obj, row) {
var div = document.getElementById(obj);
var img = document.getElementById("img" + obj);
if (div.style.display == "none") {
div.style.display = "block";
if (row == "alt") {
img.src = "../App_Themes/Admin/img/minus.png";
} else {
img.src = "../App_Themes/Admin/img/minus.png";
}
img.alt = "Close to view other Payroll info";
} else {
div.style.display = "none";
if (row == "alt") {
img.src = "../App_Themes/Admin/img/plus.png";
} else {
img.src = "../App_Themes/Admin/img/plus.png";
}
img.alt = "Expand to show Payroll Details";
}
}
</script>
<script type="text/javascript">
function AssignExportHTML() {
document.getElementById('<%=hidGridView.ClientID%>').value = htmlEscape(forExport.innerHTML);
}
function htmlEscape(str) {
return String(str)
.replace(/&/g, '&')
.replace(/"/g, '"')
.replace(/'/g, ''')
.replace(/</g, '<')
.replace(/>/g, '>');
}
</script>
I need to export the nested child gridview to excel with grouping (subtotal, Grand total), but when I export grouping row is only a blank row, so I try this code but it cannot work with nested gridview
So how to do, because when debugging, null value error occur. I think because Hidden Field value is null and I cannot get the div forExport in the Parent Gridview.And this is the code behind:
public override void VerifyRenderingInServerForm(Control control)
{
/* Confirms that an HtmlForm control is rendered for the specified ASP.NET
server control at run time. */
}
protected void ExportExcel(object sender, EventArgs e)
{
grvPayroll.AllowPaging = false;
var grvPayrollDetails = new GridView();
for (var i = 0; i < grvPayroll.Rows.Count; i++)
{
grvPayrollDetails = (GridView) grvPayroll.Rows[i].FindControl("grvPayrollDetails");
}
Response.Clear();
Response.Buffer = true;
Response.AddHeader("content-disposition", "attachment;filename=PayrollExport.xls");
Response.Charset = "UTF-8";
Response.ContentType = "application/vnd.ms-excel";
using (var sw = new StringWriter())
{
grvPayrollDetails.AllowPaging = false;
BindGrid(SortField);
grvPayrollDetails.Font.Name = "Times New Roman";
grvPayrollDetails.BackColor = Color.Transparent;
grvPayrollDetails.GridLines = GridLines.Both;
grvPayrollDetails.HeaderStyle.VerticalAlign=VerticalAlign.Middle;
sw.Write(System.Web.HttpUtility.HtmlDecode(hidGridView.Value));
Response.Write(Regex.Replace(sw.ToString(), "(<a[^>]*>)|(</a>)", " ", RegexOptions.IgnoreCase));
Response.Flush();
Response.End();
}
}
I referred this link :Exporting to Excel from GridView when grid changed by code behind
For accessing id of asp.net controls you have to use ClientID as below
document.getElementById('<%=hidGridView.ClientID%>').value = htmlEscape(document.getElementById("forExport").innerHTML);
In one of the webpage, I have RadGrid inside FormView Control
i.e., as below markup:
<asp:FormView ID="fvIPRForm" runat="server" DefaultMode="Insert" DataKeyNames="RequestID"
DataSourceID="odsIPRForm" EnableModelValidation="True" OnItemInserting="fvIPRForm_ItemInserting"
OnDataBound="fvIPRForm_DataBound" OnItemUpdating="fvIPRForm_Updating" OnItemCommand="fvIPRForm_ItemCommand">
<%-- Create New IPR--%>
<InsertItemTemplate>
<telerik:RadMultiPage ID="RadMultiPage5" runat="server" SelectedIndex="0" Width="100%">
<telerik:RadPageView ID="RadPageView4" runat="server" Width="100%">
<telerik:RadAjaxPanel ID="RadAjaxPanel4" runat="server">
//RadGrid
<telerik:RadGrid ID="RGGSTAcCode" runat="server" AutoGenerateColumns="false"....>
//other code
<telerik:GridTemplateColumn UniqueName="AccountCode" HeaderText="Account Code">
<ItemTemplate>
<asp:Label ID="lblAcCode" Text='<%# Eval("AccountCode") %>' runat="server"></asp:Label>
</ItemTemplate>
<EditItemTemplate>
<asp:Label ID="lblAcCode2" runat="server" Text='<%# Eval("AccountCode") + " - " + Eval("AccountDescription")%>' Visible="false"></asp:Label>
<telerik:RadComboBox ID="ddlAccountCode" runat="server" Height="200" Width="260"
AllowCustomText="true" onclienttextchange="OnClientTextChange">
</telerik:RadComboBox>
<asp:Button ID="btnSearch" runat="server" Text="Search" OnClick="btnSearch_Click" OnClientClick="ButtonClicked()" UseSubmitBehavior="true" />
</EditItemTemplate>
</telerik:GridTemplateColumn>
</telerik:RadGrid>
</telerik:RadAjaxPanel>
</telerik:RadPageView>
</telerik:RadMultiPage>
</InsertItemTemplate>
<%-- Edit IPR--%>
<EditItemTemplate>
<telerik:RadMultiPage ID="RadMultiPage5" runat="server" SelectedIndex="0" Width="100%">
<telerik:RadPageView ID="RadPageView4" runat="server" Width="100%">
<telerik:RadAjaxPanel ID="RadAjaxPanel4" runat="server">
//RadGrid
<telerik:RadGrid ID="RGGSTAcCode" runat="server" AutoGenerateColumns="false"....>
//other code
<telerik:GridTemplateColumn UniqueName="AccountCode" HeaderText="Account Code">
<ItemTemplate>
<asp:Label ID="lblAcCode" Text='<%# Eval("AccountCode") %>' runat="server"></asp:Label>
</ItemTemplate>
<EditItemTemplate>
<asp:Label ID="lblAcCode2" runat="server" Text='<%# Eval("AccountCode") + " - " + Eval("AccountDescription")%>' Visible="false"></asp:Label>
<telerik:RadComboBox ID="ddlAccountCode" runat="server" Height="200" Width="260"
AllowCustomText="true" onclienttextchange="OnClientTextChange">
</telerik:RadComboBox>
<asp:Button ID="btnSearch" runat="server" Text="Search" OnClick="btnSearch_Click" OnClientClick="ButtonClicked()" UseSubmitBehavior="true" />
</EditItemTemplate>
</telerik:GridTemplateColumn>
</telerik:RadGrid>
</telerik:RadAjaxPanel>
</telerik:RadPageView>
</telerik:RadMultiPage>
</EditItemTemplate>
<%-- View IPR--%>
<ItemTemplate>
<telerik:RadMultiPage ID="RadMultiPage5" runat="server" SelectedIndex="0" Width="100%">
<telerik:RadPageView ID="RadPageView4" runat="server" Width="100%">
<telerik:RadAjaxPanel ID="RadAjaxPanel4" runat="server">
//RadGrid
<telerik:RadGrid ID="RGGSTAcCode" runat="server" AutoGenerateColumns="false"....>
//other code
<telerik:GridTemplateColumn UniqueName="AccountCode" HeaderText="Account Code">
<ItemTemplate>
<asp:Label ID="lblAcCode" Text='<%# Eval("AccountCode") %>' runat="server"></asp:Label>
</ItemTemplate>
<EditItemTemplate>
<asp:Label ID="lblAcCode2" runat="server" Text='<%# Eval("AccountCode") + " - " + Eval("AccountDescription")%>' Visible="false"></asp:Label>
<telerik:RadComboBox ID="ddlAccountCode" runat="server" Height="200" Width="260"
AllowCustomText="true" onclienttextchange="OnClientTextChange">
</telerik:RadComboBox>
<asp:Button ID="btnSearch" runat="server" Text="Search" OnClick="btnSearch_Click" OnClientClick="ButtonClicked()" UseSubmitBehavior="true" />
</EditItemTemplate>
</telerik:GridTemplateColumn>
</telerik:RadGrid>
</telerik:RadAjaxPanel>
</telerik:RadPageView>
</telerik:RadMultiPage>
</ItemTemplate>
</asp:FormView>
Now, I try to get the RadGrid -- EditItemTemplate -- Button control
inside JavaScript to make it visible true/false based on text length that user enter in RadComboBox.
Below is my JavaScript:
<script lang="javascript" type="text/javascript">
function OnClientTextChange(sender, eventArgs) {
//alert("You typed " + sender.get_text());
var len = sender.get_text().length;
alert(len);
var form = $find("<%#RGGSTAcCode.ClientID%>").get_masterTableView();
alert(form);
}
</script>
When I run my web page, I always get below error:
The name 'RGGSTAcCode' does not exist in the current context
I tried to change the JavaScript code as below:
var form = document.getElementById('<%=fvIPRForm.FindControl("RGGSTAcCode").ClientID%>');
var masterTable = form.get_masterTableView();
alert(masterTable);
but then I get [object Object] in "alert". What is wrong in my code?
Edit
Tried below solution, all working except Buttons are not disabled/enabled inside if/else:
function onTextChange(sender, args) {
//alert("You typed " + sender.get_text());
var len = sender.get_text().length;
alert(len);
var comboID = sender.get_id();
var btnSearchID = comboID.replace("ddlAccountCode", "btnSearch");
alert("Alert 1: " + btnSearchID); //getting : contentplaceholder_fviIPRForm_RGGSTAcCode_btnSearch
var btnCtrl = $get(btnSearchID);
alert("Alert 2: " + btnCtrl); //getting : [object HTMLInputElement]
if (len > 5)
{
alert("greater");
btnCtrl.set_enabled(true);
btnsearch.set_enabled(true); // enable search button
}
else
{
alert("less");
btnCtrl.set_enabled(false);
btnsearch.set_enabled(false); // disable search button
}
}
This might be the answer you want....
Not the best but is working..
.aspx
<asp:FormView ID="fv" runat="server" DefaultMode="Insert" OnDataBound="fv_DataBound">
<InsertItemTemplate>
<telerik:RadMultiPage ID="RadMultiPage5" runat="server"
SelectedIndex="0" Width="100%">
<telerik:RadPageView ID="RadPageView4" runat="server" Width="100%">
<telerik:RadAjaxPanel ID="RadAjaxPanel4" runat="server">
<telerik:RadGrid ID="RadGrid1" runat="server"
AutoGenerateColumns="false"
OnNeedDataSource="RadGrid1_NeedDataSource">
<MasterTableView>
<Columns>
<telerik:GridTemplateColumn HeaderText="Acc">
<ItemTemplate>
<asp:Label ID="lbl" runat="server"
Text='<%# Eval("Acc") %>'></asp:Label>
<telerik:RadComboBox ID="ddlAccountCode"
runat="server" Height="200" Width="260"
AllowCustomText="true"
OnClientTextChange="onTextChange">
<Items>
<telerik:RadComboBoxItem Text="Gg" />
<telerik:RadComboBoxItem Text="Gg1" />
<telerik:RadComboBoxItem Text="Gg3" />
</Items>
</telerik:RadComboBox>
<telerik:RadButton ID="btnSearch" runat="server" Text="Search" />
</ItemTemplate>
</telerik:GridTemplateColumn>
</Columns>
</MasterTableView>
</telerik:RadGrid>
</telerik:RadAjaxPanel>
</telerik:RadPageView>
</telerik:RadMultiPage>
</InsertItemTemplate>
</asp:FormView>
Javascript
<telerik:RadCodeBlock ID="rcb" runat="server">
<script type="text/javascript">
function onTextChange(sender, args) {
var grid = $find('<%=fv.FindControl("RadGrid1").ClientID %>');
var gridMasterData = grid.get_masterTableView();
var dataItem = gridMasterData.get_dataItems();
var length = dataItem.length;
// Loop
for (var i = 0; i < length; i++) {
// Find Control
var comboBox = dataItem[i].findControl("ddlAccountCode");
// Check
if (comboBox != undefined) {
if (sender.get_id() == comboBox.get_id()) {
// Find Button
var btn = dataItem[i].findControl("btnSearch");
var item = sender.get_text();
// Check
if (item.length > 5) {
if (btn != undefined) btn.set_visible(true);
}
else btn.set_visible(false);
break;
}
else
continue;
}
}
}
</script>
</telerik:RadCodeBlock>
.cs
protected void Page_Load(object sender, EventArgs e)
{
// Check
if (!IsPostBack)
{
// Variable
DataTable dt = new DataTable();
DataTable dt1 = new DataTable();
dt.Columns.Add("Acc");
dt1.Columns.Add("a");
// Loop
for (int i = 0; i < 2; i++)
dt.Rows.Add("a " + i);
dt1.Rows.Add("AAAA");
ViewState["Data"] = dt;
// Bind
fv.DataSource = dt1;
fv.DataBind();
dt.Dispose();
dt1.Dispose();
}
}
protected void fv_DataBound(object sender, EventArgs e)
{
// FindControl
RadGrid RadGrid1 = fv.FindControl("RadGrid1") as RadGrid;
// Check
if (RadGrid1 != null)
{
RadGrid1.DataSource = ViewState["Data"] as DataTable;
RadGrid1.DataBind();
}
}
protected void RadGrid1_NeedDataSource(object sender, GridNeedDataSourceEventArgs e)
{
RadGrid rg = fv.FindControl("RadGrid1") as RadGrid;
// Check
if (rg != null)
{
rg.DataSource = ViewState["Data"] as DataTable;
}
}
Below code is working fine based on my requirement:
function onTextChange(sender, args) {
var len = sender.get_text().length;
//alert(len);
var comboID = sender.get_id();
var btnSearchID = comboID.replace("ddlAccountCode", "btnSearch");
var btnCtrl = document.getElementById(btnSearchID);
if (len >= 5)
{
btnCtrl.disabled = false;
//btnCtrl.style.display = "";
}
else
{
btnCtrl.disabled = true;
//btnCtrl.style.display = "none";
}
}
I am able to check a column of checkbox when I click the gridview row, however it limits only to a particluar column, when I click on the column of the checkbox, it it is not wkorking.
Here's the case, When I click the any where on this part, it worked well. the checkbox still checking.
but when I click on this part, it doesn't work already.
codes are here
$(document).ready(function () {
$('body').on('click', 'tr.dataRow', function () {
var checked = $(this).find('input[id*=chkBusinessSelected]').prop('checked');
$(this).find('input[id*=chkBusinessSelected]').prop('checked', !checked);
});
});
var prm = Sys.WebForms.PageRequestManager.getInstance();
prm.add_endRequest(function () {
$('body').on('click', 'tr.dataRow', function () {
var checked = $(this).find('input[id*=chkBusinessSelected]').prop('checked');
$(this).find('input[id*=chkBusinessSelected]').prop('checked', !checked);
});
});
<asp:GridView ID="grdBusiness" runat="server" AutoGenerateColumns="False" BackColor="White" BorderColor="#DEDFDE" BorderStyle="None" BorderWidth="1px" CellPadding="4" ForeColor="Black" GridLines="Vertical" Width="420px" ShowHeaderWhenEmpty="True" EmptyDataText="No records Found" OnRowDataBound="grdBusiness_RowDataBound" DataSourceID="SqlDataSource3" >
<AlternatingRowStyle BackColor="White" />
<Columns>
<asp:TemplateField>
<ItemTemplate>
<asp:CheckBox ID="chkBusinessSelected" runat="server" />
</ItemTemplate>
</asp:TemplateField>
<asp:BoundField DataField="Code" HeaderText="Code" SortExpression="Code" />
<asp:BoundField DataField="Business Type" HeaderText="Business Type" SortExpression="Business Type" />
</Columns>
<FooterStyle BackColor="#CCCC99" />
<HeaderStyle BackColor="#6B696B" Font-Bold="True" ForeColor="White" />
<PagerStyle BackColor="#F7F7DE" ForeColor="Black" HorizontalAlign="Right" />
<RowStyle BackColor="#F7F7DE" />
<SelectedRowStyle BackColor="#90FF90" Font-Bold="True" ForeColor="Black" />
<SortedAscendingCellStyle BackColor="#FBFBF2" />
<SortedAscendingHeaderStyle BackColor="#848384" />
<SortedDescendingCellStyle BackColor="#EAEAD3" />
<SortedDescendingHeaderStyle BackColor="#575357" />
</asp:GridView>
protected void grdBusiness_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
e.Row.CssClass = "dataRow";
}
}
I am edited #UsmanKhalid 's answer and it worked for me:
$(function () {
$("#<%=grdBusiness.ClientID %> td").click(function () {
selectRow($(this).closest("tr"));
});
});
function selectRow(row) {
var firstInput = row[0].getElementsByTagName('input')[0];
firstInput.checked = !firstInput.checked;
}
Try this code:
$(function () {
$("[id*=GridView] td").click(function () {
selectRow($(this).closest("tr"));
});
});
function selectRow(row)
{
var firstInput = row.getElementsByTagName('input')[0];
firstInput.checked = !firstInput.checked;
}
Try the following
$('tr.dataRow').click(function(){
var chkBox = $(this).find('input[type=checkbox]');
chkBox.prop("checked", !chkBox.prop("checked"));
});
I am trying to create a file upload control dynamically for updating word documents. I have the following code in my aspx page.
<asp:GridView ID="gvDetails" runat="server" AutoGenerateColumns="false" DataKeyNames="FilePath" EmptyDataText="No documents attached" >
<HeaderStyle BackColor="Purple" Font-Bold="true" ForeColor="White" />
<Columns>
<asp:TemplateField HeaderText="FilePath">
<ItemTemplate>
<asp:LinkButton ID="lnkDownload" runat="server" Text="My Document" OnClick="lbDownloadDocument_Click"></asp:LinkButton>
<img src="Image/delete.jpg" alt="" onclick="AddFile()" /><br />
<br />
<asp:Button ID="Button1" runat="server" Text="Update" OnClick="Button2_Click" />
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
I have the following code in my .cs page.
protected void Button2_Click(object sender, EventArgs e)
{
for (int i = 0; i < Request.Files.Count; i++)
{
HttpPostedFile PostedFile = Request.Files[i];
if (PostedFile.ContentLength > 0)
{
string FileName = System.IO.Path.GetFileName(PostedFile.FileName);
PostedFile.SaveAs(Server.MapPath("~/Files/") + FileName);
}
}
}
And my script is :
<script type="text/javascript">
var i = 1;
function AddFile() {
i++;
var div = document.createElement('DIV');
div.innerHTML = '<input id="file' + i + '" name = "file' + i + '" type="file" /><img src="~/Image/delete.jpg" alt="Remove" onclick = "RemoveFile(this)" />';
document.getElementById("divFile").appendChild(div);
}
function RemoveFile(file) {
document.getElementById("divFile").removeChild(file.parentNode);
}
</script>
But Somehow this code is not working. I don't have much idea of file upload control. Please help me with it. Should I use an Update panel ?
I am trying to validate that each radiobuttonlist has been selected. the radiobuttonlist is dynamically created from a sql database. The following line errors out "if (MyRadio[j].checked) {", the error is "checked' is null or not an object". The following is the code. Thank you
<asp:Content ID="Content2" ContentPlaceHolderID="ContentPlaceHolder2" runat="Server">
<cc1:TabContainer ID="TabContainer1" runat="server" ActiveTabIndex="0" CssClass="ajax__myTab" Width="100%" ScrollBars="Horizontal">
<cc1:TabPanel ID="TabPanel1" runat="server" HeaderText="" Enabled="true">
<HeaderTemplate>Main</HeaderTemplate>
<ContentTemplate>
<table cellpadding="3" cellspacing="1">
<tr>
<td style="text-align: right">Audit Status:</td>
<td>
<asp:DropDownList ID="ddlAuditStatus" runat="server">
<asp:ListItem>InProgress</asp:ListItem>
<asp:ListItem>Completed</asp:ListItem>
</asp:DropDownList>
</td>
</tr>
</table>
</ContentTemplate>
</cc1:TabPanel>
<cc1:TabPanel ID="TabPanel2" runat="server" HeaderText="" Enabled="true">
<HeaderTemplate>Questions</HeaderTemplate>
<ContentTemplate>
<asp:GridView ID="GridViewQuestions" runat="server" AutoGenerateColumns="False" BackColor="White" BorderColor="#999999" BorderStyle="Solid" BorderWidth="1px" CellPadding="5" CellSpacing="1" DataKeyNames="Pkey" DataSourceID="SqlDataSource1" ForeColor="Black" GridLines="Vertical">
<FooterStyle BackColor="#CCCCCC" />
<Columns>
<asp:TemplateField>
<ItemTemplate>
<asp:Label ID="lblQuestion" runat="server"></asp:Label>
<asp:HiddenField ID="hdnPkey" runat="server" Value='<%# Bind("Pkey") %>' />
<asp:HiddenField ID="hdnRequiresAnAnswer" runat="server" Value='<%# Bind("RequiresAnAnswer") %>' />
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Answer">
<ItemTemplate>
<asp:RadioButtonList ID="RadioButtonList1" runat="server" RepeatDirection="Horizontal" Visible="false">
<asp:ListItem>Yes</asp:ListItem>
<asp:ListItem>No</asp:ListItem>
<asp:ListItem>N/A</asp:ListItem>
</asp:RadioButtonList>
</ItemTemplate>
<HeaderStyle Width="130px" />
<ItemStyle Width="130px" />
</asp:TemplateField>
<PagerStyle BackColor="#999999" ForeColor="Black" HorizontalAlign="Center" />
<SelectedRowStyle BackColor="#000099" Font-Bold="True" ForeColor="White" />
<HeaderStyle BackColor="Silver" Font-Bold="True" ForeColor="Black" />
<AlternatingRowStyle BackColor="#CCCCCC" />
</asp:GridView>
</ContentTemplate>
</cc1:TabPanel>
</cc1:TabContainer>
<script type="text/javascript">
function fcnUpdateMain() {
var MyStatus = document.getElementById("<%=ddlAuditStatus.ClientID%>").value
var grid = document.getElementById("<%= GridViewQuestions.ClientID %>");
if (grid.rows.length > 0) {
for (i = 2; i < grid.rows.length + 1; i++) {
if (i < 10) {
i = "0" + i
} else {
i = i
}
var MyReqAnswer = document.getElementById("ctl00_ContentPlaceHolder2_TabContainer1_TabPanel2_GridViewQuestions_ctl" + i + "_hdnRequiresAnAnswer").value
var MyRadio = document.getElementById("ctl00_ContentPlaceHolder2_TabContainer1_TabPanel2_GridViewQuestions_ctl" + i + "_RadioButtonList1")
if (MyStatus == "Completed") {
if (MyReqAnswer == "Yes") {
var options = document.getElementsByTagName("input")
for( x = 0; x < options.length; ++x ) {
if(options[x].type == "radio") {
for (var j = 0; j < MyRadio.length; j++) {
if (MyRadio[j].checked) {
} else {
alert("You must select an answer for all questions.")
document.getElementById("ctl00_ContentPlaceHolder2_TabContainer1_TabPanel2_GridViewQuestions_ctl" + i + "_ddlProductInterest").focus()
return false;
}
}
}
}
}
}
}
}
}
</script>
I think you've already realised that RadioButtonList controls are rendered as a <table> with each radio button as an <input> within that table. Therefore getting a handle on RadioButtonList1 and trying to access it as an array using MyRadio[j] isn't going to work.
I think the following line:
var options = document.getElementsByTagName("input")
Should instead read:
var options = MyRadio.getElementsByTagName("input")
That will give you just a collection of the input tags within that RadioButtonList control rather than all those on the page. Once you have that options collection, you shouldn't need to refer to the RadioButtonList control again.
I understand that this is drastically simplified over what you have, but here's an example for you:
<form runat="server">
<asp:RadioButtonList runat="server" id="RadioButtonList1">
<asp:ListItem>Yes</asp:ListItem>
<asp:ListItem>No</asp:ListItem>
<asp:ListItem>N/A</asp:ListItem>
</asp:RadioButtonList>
<input type="button" onclick="fcnUpdateMain()" value="Click" />
<script type="text/javascript">
function fcnUpdateMain()
{
var MyRadio = document.getElementById("<%=RadioButtonList1.ClientID%>")
var options = MyRadio.getElementsByTagName("input")
var somethingChecked = false;
for( x = 0; x < options.length; ++x )
{
if (options[x].checked)
{
somethingChecked = true;
}
}
if (!somethingChecked)
{
alert("You must select an answer for all questions.")
return false;
}
}
</script>
</form>