JS code on clicking button inside GridView - c#

I have a GridView control,inside of which I am having a file upload control with a button to upload files, Each FileControl have its own upload button, I am uploading files using RowCommand Event.Now I have to show progress bar of file upload control which I have implemented like in this link's 3rd answer Link with some modification in JS
The problem I am facing is that if I click on 2nd Row's upload button of GridView,Its validating only Row's Control.
This is my Grid View
<asp:GridView ID="Grid1" runat="server" AutoGenerateColumns="false" OnRowDataBound="Grid1_RowDataBound"
OnRowCommand="Grid1_RowCommand" OnRowDeleting="Grid1_RowDeleting"
CssClass="table">
<Columns>
<asp:TemplateField HeaderText="Files" ItemStyle-HorizontalAlign="Left" HeaderStyle-CssClass="GridViewHeader">
<ItemTemplate>
<asp:FileUpload ID="File1" runat="server" Width="98%" CssClass="filestat" />
<asp:Button ID="btnuploadfiles" runat="server" CommandName="upload" Text="Upload" OnClientClick="return ProgressBar('File1')" />
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
and my JS code
function ProgressBar(Id) {
var fileControl = GetClientID(Id).attr("id");
if (document.getElementById(fileControl).value != "") {
$("#divUpload").fadeIn("slow");
$('#popup_box').fadeIn("slow");
document.getElementById("divUpload").style.height = document.body.clientHeight + 'px';
id = setInterval("progress()", 20);
return true;
}
else {
alert("Select a file to upload");
return false;
}
}
//This function returns me ClientID of the server control
function GetClientID(id, context) {
var el = $("#" + id, context);
if (el.length < 1)
el = $("[id$=_" + id + "]", context);
return el;
}
I also have tried setting OnClientClick from RowDataBound,but its still validating only first Row.
protected void Grid1_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
var btnupd = (Button)e.Row.FindControl("btnuploadfiles");
btnupd.OnClientClick = "return ProgressBar('File1')";
}
}

Try something like the following;
$("#<%=Grid1.ClientID%> tr").click(function(){
alert("Row clicked");
});
I think using the ClientID function would be more suitable and clear for you. Getting the tr clicked, you should be able to read the cells in the actual array of tds then.
Try adding this
protected void Grid1_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
var button = (Button)e.Row.FindControl("btnuploadfiles");
var fileUpload = (FileUpload)e.Row.FindControl("File1");
string className = "class_" + new Random().Next();
button.Attributes.Add("class", "rowClick");
fileUpload.Attributes.Add("class", "rowClick");
button.Attributes.Add("customClass", className);
button.Attributes.Add("customClass", className);
}
}
And for script add this:
<script>
$(document).ready(function () {
$(".rowClick").click(function () {
var customClass = this.attr("customClass");
alert("Now the current row you selected has this as a common class : " + customClass);
});
});
</script>

Related

How to call a function when drop down list in gridview is changed?

I have a GridView and for one of the columns I'm using a drop down list that displays a list of users:
<asp:GridView style="float:left"
ID="gvBookings"
ShowHeaderWhenEmpty="true"
CssClass="tblResults"
runat="server"
OnRowDataBound="gvBookings_RowDataBound"
DataKeyField="ID"
AutoGenerateColumns="false"
allowpaging="false"
<Columns>
<asp:BoundField DataField="FinishDate" HeaderText="Finish Date"></asp:BoundField>
<asp:TemplateField HeaderText="Time Spent By">
<ItemTemplate>
<asp:DropDownList id="ddlUsers" runat="server" ></asp:DropDownList>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
In the code behind I need to call a function that updates the database when the drop down list is changed. I have done this already for the FinishDate column so is there a similar way to do this for the drop down menu?
Code behind:
protected void gvBookings_RowDataBound(object sender, GridViewRowEventArgs e)
{
BHTaskClass.BookingTask booking = (BHTaskClass.BookingTask)e.Row.DataItem;
if (e.Row.RowType == DataControlRowType.DataRow)
{
foreach (TableCell c in e.Row.Cells)
{
if (count == 1)
{
string FinishTime = booking.FinishTime.HasValue ? booking.FinishTime.Value.ToString("hh':'mm") : "";
c.Text = "<input type=\"text\" id=\"txtFinishTime" + booking.ID + "\" style=\"width:70px\" type=\"text\" onblur=\"UpdateFinishTime(" + booking.ID + ",this.value)\" value=\"" + FinishTime + "\" >";
}
if (count == 2)
{
ddlUsers.SelectedValue = booking.TimeSpentName;
}
count++;
}
}
}
So when the FinishDate textbox is changed it calls the UpdateFinishTime function and this updates the database. How do I call a function for the drop down list?
ASPX
<asp:DropDownList id="ddlUsers" runat="server"
AutoPostBack="true"
OnSelectedIndexChanged="YourFunction_Changed">
</asp:DropDownList>
Code behind:
protected void YourFunction_Changed(object sender, EventArgs e)
{
//do stuff...
}
To get the Row ID you can do it as below
protected void YourFunction_Changed(object sender, EventArgs e)
{
//do stuff...
int Index = ((GridViewRow)((sender as Control)).NamingContainer).RowIndex;
// your logic follows based on the Index
}

Handle multiple delete events from grid with single events handlers asp.net

I have two grid which contains delete button and I am using RadAjaxManager which will fire ajax request from client side to server side OnajaxRequest which contain event handlers and that event handler will call my delete event like below:
<telerik:RadAjaxManager ID="RadAjaxManager2" runat="server" meta:resourcekey="RadAjaxManager1Resource1" OnAjaxRequest="RadAjaxManager2_AjaxRequest">
<AjaxSettings>
<telerik:AjaxSetting AjaxControlID="RadAjaxManager2">
<UpdatedControls>
<telerik:AjaxUpdatedControl ControlID="Grid1" />
<telerik:AjaxUpdatedControl ControlID="Grid2" />
</UpdatedControls>
</telerik:AjaxSetting>
</AjaxSettings>
</telerik:RadAjaxManager>
<telerik:RadGrid ID="Grid1" runat="server">
---
---
<telerik:GridTemplateColumn HeaderText="Action" UniqueName="Action" HeaderStyle-Width="130px">
<ItemTemplate>
<asp:ImageButton runat="server" ID="Remove1" Text="Delete" OnClientClick='<%# Eval("Id", "javascript:return DeleteData(\"{0}\");") %>' />
</ItemTemplate>
</telerik:GridTemplateColumn>
<telerik:RadGrid ID="Grid2" runat="server">
---
---
<telerik:GridTemplateColumn HeaderText="Action" UniqueName="Action" >
<ItemTemplate>
<asp:ImageButton runat="server" ID="Remove2" Text="Delete" OnClientClick='<%# Eval("Id", "javascript:return DeleteData(\"{0}\");") %>' />
</ItemTemplate>
</telerik:GridTemplateColumn>
function DeleteData(Id) {
var ajaxManager = null;
var action = 'Remove';
ajaxManager = $find("ctl00_cphMain_RadAjaxManager2");
var arg = action + "," + Id; //Remove,1(1 indicates id of record to remove from grid)
ajaxManager.ajaxRequest(arg);This line will fire below method.
}
public event EventHandler RemoveEvent;
protected void RadAjaxManager2_AjaxRequest(object sender, AjaxRequestEventArgs e)
{
var argument = (e.Argument);
var stringArray = argument.Split(",".ToCharArray());//[0]="Remove",[1]=1
if (stringArray[0] == "Remove")
{
RemoveEvent(stringArray[1], null);
}
}
After this it will call this:
protected void Page_Load(object sender, EventArgs e)
{
this.RemoveEvent += Remove1_Click;
this.RemoveEvent += Remove2_Click;
if (!IsPostBack)
{
}
}
protected void Remove1_Click(object sender, object obj)
{
}
protected void Remove2_Click(object sender, object obj)
{
}
Problem here is both this events are calling but I just want to call individual delete events on click of Remove1 and Remove2 buttons.
You do not need to subscribe to events in your code-behind i.e. no need of this.RemoveEvent+=. Instead write a single method called RemoveRecord(buttonId, recordId). I have explained this approach in a step-by-step manner as below.
First change the markup for OnClientClick. Note that we will be passing the Id of the record to delete as well as the server-side id of the button being clicked to the JavaScript function DeleteData.
OnClientClick='<%# Eval("Id", "DeleteData('{0}', 'Remove1'); return false;") %>'
OnClientClick='<%# Eval("Id", "DeleteData('{0}', 'Remove2'); return false;") %>'
Change the JavaScript Delete method. Note that we are now passing the server-side button id, so that in code-behind we can easily know which button was clicked.
function DeleteData(Id, buttonId) {
var ajaxManager = null;
ajaxManager = $find("<%=RadAjaxManager2.ClientID%>");
var arg = buttonId + "," + Id; //Remove1,1 (1 indicates id of record to remove from grid)
ajaxManager.ajaxRequest(arg);//This line will fire below method.
}
In code behind, include a single RemoveRecord method and there is no need of creating event handlers as you have done in your original code. So you should remove the following methods from your original code: Remove1_Click and Remove2_Click and also remove the code in Page_Load that subscribes to click events.
protected void RadAjaxManager2_AjaxRequest(object sender, AjaxRequestEventArgs e)
{
var stringArray = e.Argument.Split(",".ToCharArray());//[0]="Remove1" or "Remove2",[1]=id of record to delete
RemoveRecord( stringArray[0], stringArray[1]);
}
//the method below will delete data
private void RemoveRecord( buttonId, recordId)
{
if(buttonId== "Remove1")
{
//code to delete record with id of recordId
}
else if ( buttonId == "Remove2")
{
//code to delete record with id of recordId
}
}
Another Approach
If you have to have RadAjaxManager2_AjaxRequest in parent page and delete methods in child page, then add the following code at appropriate places as mentioned in their titles. But please note that the markup changes and JavaScript function changes mentioned in above approach also apply to this approach.
In Parent Page (just outside the class)
public class RemoveEventArgs : EventArgs
{
public RemoveEventArgs ( string buttonId, string recordId)
{
this.ButtonId = buttonId;
this.RecordId = recordId;
}
public string ButtonId {get;set;}
public string RecordId {get;set;}
}
Also, in same parent page change the method RadAjaxManager2_AjaxRequest to what is given below.
In Parent Page (change this existing method)
protected void RadAjaxManager2_AjaxRequest(object sender, AjaxRequestEventArgs e)
{
var stringArray = e.Argument.Split(",".ToCharArray());//[0]="Remove1",[1]=1 OR [0]="Remove2", [1] = 212
if (stringArray[0] == "Remove1" || stringArray[0] == "Remove2")
{
if(RemoveEvent!=null)
{
RemoveEvent(this, new RemoveEventArgs(stringArray[0], stringArray[1]));
}
}
}
In Child Page (change existing methods)
protected void Remove1_Click(object sender, RemoveEventArgs obj)
{
if( obj!=null && obj.ButtonId == "Remove1")
{
string recordId = obj.RecordId;
//write your code for deleting
}
}
protected void Remove2_Click(object sender, RemoveEventArgs obj)
{
if( obj!=null && obj.ButtonId == "Remove2")
{
string recordId = obj.RecordId;
//write your code for deleting
}
}
you simply just use the RadGrid_ItemCommand and pass the command argument with del button and change the command name for both remove her's a sample code for
<telerik:GridTemplateColumn HeaderText="Actions">
<ItemTemplate>
<asp:ImageButton ID="Button3" Style="width: 14px" Height="14px" ImageUrl="~/Images/Erase.png" runat="server" Text="Delete1" OnClientClick="return confirm('Are you sure you want to delete this item?');" CommandName="Delete1" CommandArgument='<%# Eval("Pid") %>' />
&nbsp &nbsp
<asp:ImageButton ID="Button3" Style="width: 14px" Height="14px" ImageUrl="~/Images/Erase.png" runat="server" Text="Delete2" OnClientClick="return confirm('Are you sure you want to delete this item?');" CommandName="Delete2" CommandArgument='<%# Eval("Pid") %>' />
</ItemTemplate>
</telerik:GridTemplateColumn>
protected void RadGrid1_ItemCommand(object sender, GridCommandEventArgs e)
{
if (e.CommandName == "Delete1")
{
}
if (e.CommandName == "Delete2")
{
}
}

How to disable button in row databound event in gridview?

i want to disable button in row data bound . when its text or value is 'Waiting for Approval'. im getting this error . Object reference not set to an instance of an object.// button.Enabled = true;
protected void GridCategoryWise_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType != DataControlRowType.DataRow)
{
return;
}
Button button = (Button)e.Row.FindControl("btnReportedlink");
string Id =((DataRowView)e.Row.DataItem)["ReportLinks"].ToString();
if (Id == "Waiting for Approval")
{
button.Enabled = false;
}
else
{
button.Enabled = true;
}
}
my aspx
<asp:TemplateField HeaderText="Reportd Link" ItemStyle-HorizontalAlign="center" >
<ItemTemplate>
<button onclick="window.open('<%#Eval("ReportLinks")%>', '_blank');" title='<%#Eval("ReportLinks")%>' id="btnReportedlink" runat="server"> Link</button>
</ItemTemplate>
<ItemStyle HorizontalAlign="Left" />
</asp:TemplateField>
Why are you using the HTML <button /> element ? use <asp:button /> web server control from asp.net for a better control over reading and disabling the server controls.
Use the OnClientClick property to specify additional client-side script that executes when a Button control's Click event is raised.
<ItemTemplate>
<asp:button onclientclick="javascript:window.open('<%#Eval("ReportLinks")%>', '_blank');"
text='<%#Eval("ReportLinks")%>' id="btnReportedlink" runat="server"/>
</ItemTemplate>
With the above setup, now you will be able to access the button in row data bound event with NO more object references error.
use DataBinder work fine
protected void GridCategoryWise_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType != DataControlRowType.DataRow)
{
return;
}
Button button = (Button)e.Row.FindControl("btnReportedlink");
string Id = Convert.ToInt32(DataBinder.Eval(e.Row.DataItem, "ReportLinks"));
if (Id == "Waiting for Approval")
{
button.Enabled = false;
}
else
{
button.Enabled = true;
}
}

How to upload image file in gridview?

I have a gridview that shows an image as part of a column. In Edit mode, I would like to let the user upload a new image file, so I'm using the FileUpload control in the edit part of the template.
When I click on update it's showing me this:
My code:
protected void GridView1_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
Label lb = GridView1.HeaderRow.FindControl("Label1") as Label;
GridViewRow row = GridView1.Rows[e.RowIndex];
FileUpload fu = row.Cells[0].FindControl("fileupload") as FileUpload;
if (fu.HasFile)
{
string file = System.IO.Path.Combine(Server.MapPath("~/uploadedimages/"), fu.FileName);
fu.SaveAs(file);
using (Ex_RepeaterEntities entities = new Ex_RepeaterEntities())
{
Student students = (from e1 in entities.Students
where e1.Id == Convert.ToInt32(lb.Text)
select e1).First();
students.Images = file;
entities.SaveChanges();
}
}
}
After a lot of searching I found solution of above error by using this code:
protected void GridView1_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
int RowID = Convert.ToInt32(GridView1.DataKeys[e.RowIndex].Value);
FileUpload fileUpload = GridView1.Rows[e.RowIndex].FindControl("fileupload") as FileUpload;
if (fileUpload.HasFile)
{
fileUpload.SaveAs(Server.MapPath("~/uploadedimages/" + fileUpload.FileName));
}
}
and at page.aspx:
<asp:TemplateField HeaderText="Upload Image" SortExpression="Names">
<EditItemTemplate>
<asp:FileUpload runat="server" ID="fileupload" />
</EditItemTemplate>
<ItemTemplate>
<asp:Image ImageUrl="~/uploadedimages/1.jpg" runat="server" ID="image" />
</ItemTemplate>
</asp:TemplateField>
But a little problem here is to solve which is that file is not saving.
Finally got my own solution of above post. Here is code to be changed:
if (fileUpload.HasFile)
{
fileUpload.SaveAs(Server.MapPath("uploadedimages/" + fileUpload.FileName));
}

Confirmation dialog box on CommandField click [duplicate]

I want to prompt the user for confirmation when he tries to delete a record in a detail view? I have command filed in which showDeletebutton set to true.
I found how to do the confirmation for gridview, but how can I modify to match detail view?
Code:
protected void GridView_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
// loop all data rows
foreach (DataControlFieldCell cell in e.Row.Cells)
{
// check all cells in one row
foreach (Control control in cell.Controls)
{
// Must use LinkButton here instead of ImageButton
// if you are having Links (not images) as the command button.
ImageButton button = control as ImageButton;
if (button != null && button.CommandName == "Delete")
// Add delete confirmation
button.OnClientClick = "if (!confirm('Are you sure " +
"you want to delete this record?')) return;";
}
}
}
}
Anybody?
<asp:DetailsView ID="DetailsView1" runat="server" Height="50px" Width="125px"
.....
<asp:BoundField DataField="price" HeaderText="price" SortExpression="price" />
<asp:BoundField DataField="Quantity" HeaderText="Quantity"
SortExpression="Quantity" />
<asp:TemplateField ShowHeader="False">
<ItemTemplate>
<asp:LinkButton ID="LinkButton2" runat="server" CausesValidation="False"
CommandName="New" Text="New"></asp:LinkButton>
<asp:LinkButton ID="lnkDelete" runat="server" CausesValidation="False"
CommandName="Delete" Text="Delete" OnClientClick="return confirm('Are you sure you want to delete this record');"></asp:LinkButton>
</ItemTemplate>
</asp:TemplateField>
</Fields>
</asp:DetailsView
This can be done easily on the markup code. I simply added the js code to the onClientClick property of the delete button:
OnClientClick="return confirm('Are you sure you want to delete this record');"
Or if you want do this in the code behind:
protected void DetailsView1_DataBound(object sender, EventArgs e)
{
LinkButton bttn = (LinkButton)DetailsView1.FindControl("lnkDelete");
bttn.OnClientClick = "return confirm('Are you sure you want to delete this record!');";
}
I found the answer to my question.
My answer:
protected void DViewComputer_DataBound1(object sender, EventArgs e)
{
int noRow = DViewComputer.Rows.Count - 1;//get the no of record
if (noRow >0)
{
Button button = (Button)(DViewComputer.Rows[noRow].Cells[0].Controls[2]);
// Add delete confirmation
((System.Web.UI.WebControls.Button)(button)).OnClientClick = "if (!confirm('Are you sure " +
"you want to delete this record?')) return;";
}
}
Anyways thanks for your help guys.
foreach (Control control in cell.Controls)
{
// Must use LinkButton here instead of ImageButton
// if you are having Links (not images) as the command button.
ImageButton button = control as ImageButton;
if (button != null && button.CommandName == "Delete")
// Add delete confirmation
button.Attributes.Add("onclick","your javascript here");
}
Please see the below URL......
http://www.codeproject.com/Articles/32756/ASP-NET-GridView-delete-confirmation-using-asp-Com
This corrects the OP's solution. The code was translated from the code found here: http://forums.aspfree.com/net-development-11/confirm-button-when-deleting-detailsview-120113-2.html
protected void dvEvent_DataBound(object sender, EventArgs e)
{
int commandRowIndex = dvEvent.Rows.Count - 1;
if (commandRowIndex > 0)
{
DetailsViewRow commandRow = dvEvent.Rows[commandRowIndex];
DataControlFieldCell cell = (DataControlFieldCell)commandRow.Controls[0];
foreach (Control ctrl in cell.Controls)
{
if (ctrl is ImageButton)
{
ImageButton ibt = (ImageButton)ctrl;
if (ibt.CommandName == "Delete")
{
ibt.ToolTip = "Click here to Delete";
ibt.CommandName = "Delete";
ibt.Attributes["onClick"] = "if (!confirm('Are you sure " +
"you want to delete this record?')) return;";
}
}
}
}
}

Categories

Resources