<asp:UpdatePanel ID="UpdatePanel10" runat="server">
<ContentTemplate>
<center>
<asp:GridView ID="gridInboxMessage" runat="server" AllowPaging="True"
AllowSorting="True"
AutoGenerateColumns="False" DataSourceID="LinqDataSource1" OnSelectedIndexChanged="gridInboxMessage_SelectedIndexChanged"
onrowdeleted="gridInboxMessage_RowDeleted"
onrowdeleting="gridInboxMessage_RowDeleting">
<Columns>
<asp:CommandField ShowSelectButton="True" SelectText="show text" />
<asp:TemplateField >
<ItemTemplate>
<asp:Button ID="btnDeleteInbox" Text="delete" OnClick="btnDeleteInbox_Click" runat="server" />
</ItemTemplate>
</asp:TemplateField>
<asp:BoundField DataField="Row" HeaderText="row" ReadOnly="True" SortExpression="Row" />
<asp:TemplateField SortExpression="Body" HeaderText="متن">
<ItemTemplate>
<asp:Label ID="MyBody" runat="server" Text='<%# TruncateText(Eval("Body"))%>'>
</asp:Label>
<asp:Label ID="fullBodyRecieve" Visible="false" runat="server" Text='<%# Eval("Body")%>'>
</asp:Label>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
<asp:LinqDataSource ID="LinqDataSource1" AutoSort="true"
runat="server" ContextTypeName="DataClassesDataContext"
Select="new (Row,Title, Body, Sender, Date1)" TableName="PrivateMessages"
Where="Receptor == #Receptor" ondeleted="LinqDataSource1_Deleted"
ondeleting="LinqDataSource1_Deleting">
<WhereParameters>
<asp:QueryStringParameter Name="Receptor" QueryStringField="idCompany" Type="String" />
</WhereParameters>
</asp:LinqDataSource>
</ContentTemplate>
</asp:UpdatePanel>
protected void btnDeleteInbox_Click(object sender, EventArgs e)
{
GridViewRow row = gridInboxMessage.SelectedRow;
var inboxMessage = (from b in dc.PrivateMessages where b.Row.ToString() == row.Cells[0].Text select b).Single();
dc.PrivateMessages.DeleteOnSubmit(inboxMessage);
dc.SubmitChanges();
}
btnDeleteInbox_Click doe not work??This method is never executed
protected void gridInboxMessage_RowDeleted(object sender, GridViewDeletedEventArgs e)
{
GridViewRow row = gridInboxMessage.SelectedRow;
var inboxMessage = (from b in dc.PrivateMessages where b.Row.ToString() == row.Cells[0].Text select b).Single();
dc.PrivateMessages.DeleteOnSubmit(inboxMessage);
dc.SubmitChanges();
}
gridInboxMessage_RowDeleted doe not work??This method is never executed
protected void gridInboxMessage_RowDeleting(object sender, GridViewDeleteEventArgs e)
{
GridViewRow row = gridInboxMessage.SelectedRow;
var inboxMessage = (from b in dc.PrivateMessages where b.Row.ToString() == row.Cells[0].Text select b).Single();
dc.PrivateMessages.DeleteOnSubmit(inboxMessage);
dc.SubmitChanges();
}
gridInboxMessage_RowDeleting doe not work??This method is never executed
The RowDeleted and RowDeleting event handlers are probably not getting executed because it does not appear as though anything is calling the delete command. You're not generating a delete button and your custom button is not calling the delete command. See the example in the RowDeleting event documentation for how to implement the use of the event. Notice that the example sets the "AutoGenerateDeleteButton" property to true. When they user clicks that button, the RowDeleting and then RowDeleted events will fire.
I'm not sure why your custom button's handler is not getting executed. Can you confirm that your page is indeed posting back? Are you able to debug through the code to see what steps it is taking during the postback? As Muhammad requested, will you please include your page load code as well as any other relevant code?
Related
I Have a GridView which conntains multiple records and couple of Link Buttons Named Edit and Detail. Now i want to Get the Name of the User (NOT Index), when a user click on Detail Link Button. Like "Name", "FatherName" etc
Here is the .aspx code
<asp:GridView ID="dgvEmployeesInformation" runat="server" CssClass=" table table-bordered table-hover table-responsive" DataKeyNames="Id" AutoGenerateColumns="False" OnRowCommand="dgvEmployeesInformation_RowCommand" OnRowDataBound="dgvEmployeesInformation_RowDataBound" AllowPaging="True" AllowSorting="True" OnPageIndexChanging="dgvEmployeesInformation_PageIndexChanging">
<%--1st Column--%>
<Columns>
<asp:BoundField HeaderText="ID" DataField="Id" ControlStyle-BackColor="#0066ff" Visible="False">
<ControlStyle BackColor="#0066FF"></ControlStyle>
</asp:BoundField>
<asp:BoundField HeaderText="Name" DataField="Name" />
<asp:BoundField HeaderText="Employee No" DataField="EmployeeNo" />
<asp:BoundField HeaderText="Father Name" DataField="FatherName" />
<asp:HyperLinkField DataNavigateUrlFields="Id" DataNavigateUrlFormatString="AddEmployeeBasic1.aspx?thid={0}" HeaderText="Update" NavigateUrl="~/AddEmployeeBasic1.aspx" Text="Edit" />
<asp:TemplateField HeaderText="Action" ShowHeader="True">
<ItemTemplate>
<asp:LinkButton ID="lbDelete" runat="server" CausesValidation="False" CommandName="Delete" Text="Delete"></asp:LinkButton>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField>
<ItemTemplate>
<asp:LinkButton runat="server" ID="lbDetail" OnClick="lbDetail_Click" DataNavigateUrlFields="Id" DataNavigateUrlFormatString="EmployeesDetails.aspx?EmpID={0}" NavigateUrl="~/EmployeesDetails.aspx" HeaderText="Show Detail" Text="Detail"></asp:LinkButton>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
Here is the lbDetail_Click Code
protected void lbDetail_Click(object sender, EventArgs e)
{
GridViewRow clickedRow = ((LinkButton)sender).NamingContainer as GridViewRow;
Label lblUserName = (Label)clickedRow.FindControl("Name");
EmployeeID.EmpName = lblUserName.ToString();
}
When i put my program on Debugging mode, the lblUserName return NULL
Here is the picture.
What i want is that, when a user click on Detail LinkButton, then on lbDetail Click event, it gets the Name of the Employee and store it in a static variable. Following is the picture
I don't understand how to solve this problem. Please help me through this. Your help will be really appreciated.
I would just add data attributes to the details button then get it's values at code behind.
For example:
1.) Add new data-myData='<%# Eval("Name") %>' attribute and its value to button
<asp:TemplateField>
<ItemTemplate>
<asp:LinkButton runat="server" ID="lbDetail" OnClick="lbDetail_Click" Text="Detail" data-ID='<%# Eval("ID") %>' data-myData='<%# Eval("Name") %>' ></asp:LinkButton>
</ItemTemplate>
</asp:TemplateField>
2.) Get those data from event handler
protected void lbDetail_Click(object sender, EventArgs e)
{
LinkButton button = (LinkButton)sender;
var name = (string)button.Attributes["data-myData"];
var selectedID = (string)button.Attributes["data-ID"];
Session["selectedID"] = selectedID ;
}
lblUserName is null because it's not a Label, but a BoundField.
What you could do it get the Cell value.
protected void lbDetail_Click(object sender, EventArgs e)
{
GridViewRow clickedRow = ((LinkButton)sender).NamingContainer as GridViewRow;
Label1.Text = clickedRow.Cells[1].Text;
}
Or use a TemplateField that does contain a Label Name
<asp:TemplateField HeaderText="Name">
<ItemTemplate>
<asp:Label ID="Name" runat="server" Text='<%# Eval("Name")%>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
Here is how your code should look:
protected void lbDetail_Click(object sender, EventArgs e)
{
GridViewRow clickedRow = ((LinkButton)sender).NamingContainer as GridViewRow;
var username = clickedRow.Cells[1].Text;
if(string.IsNullOrEmpty(username))
{
return;
}
EmployeeID.EmpName = username;
}
i have a system that adds items into the DataGrid, my question is how can i use the delete button? when the user wants the item deleted, user will press the button to delete the row, but i cant seem to make it work. thank you!
<asp:GridView runat="server" ID="gridview" CssClass="table-hover" AutoGenerateColumns="true" HeaderStyle-BackColor="CornflowerBlue" BackColor="White" BorderWidth="5" BorderColor="CornflowerBlue" OnSelectedIndexChanged="gridview_SelectedIndexChanged" CellPadding="8"
CellSpacing="0" Width="100%" OnRowDeleting="gridview_RowDeleting" EmptyDataText="No records to display">
<HeaderStyle BackColor="CornflowerBlue"></HeaderStyle>
<Columns>
<asp:CommandField ShowDeleteButton="true" ButtonType="Button" />
<asp:TemplateField ItemStyle-Width="25px" HeaderText="">
<ItemTemplate>
<asp:ImageButton ID="lnkEdit" runat="server" ImageUrl="~/Images/Icons/Modify.png" OnClick="Edit" />
<%--<asp:LinkButton ID="lnkEdit" runat="server" Text="Edit" OnClick="Edit"></asp:LinkButton>--%>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
here is my script
<script runat="server">
void gridview_RowDeleting(object sender, GridViewDeleteEventArgs e)
{
TableCell cell = gridview.Rows[e.RowIndex].Cells[2];
}
</script>
grid view picture
In Gridview add OnRowCommand="gridview_RowCommand"
CommandField can work but I go like this:
<asp:TemplateField ItemStyle-Width="25px" HeaderText="">
<ItemTemplate>
<asp:Button ID="lnkDel" runat="server" Text="Delete" CommandName="Del" CommandArgument='<%#Eval("ID")%>' />
</ItemTemplate>
</asp:TemplateField>
In code behind
protected void gridview_RowCommand(object sender, GridViewCommandEventArgs e)
{
if (e.CommandName == "Del") {
//Get Command Argument
int IdToDelete = Convert.ToInt32( e.CommandArgument.ToString());
//Your Delete Command
//Rebind GridView
}
}
I'm added a template field and made it a button click event. Then I'm trying to sent the value to event method and want to some operation with that value. I wrote following code. It has no compilation error but when i click Present browser shows following message:
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.
Code:
<div>
<asp:Panel ID="PanelAllEmployee" runat="server" Height="400px">
<asp:GridView ID="GridViewAllEmployee" runat="server" AutoGenerateColumns="False" style="position:absolute;left:219px; top:202px;" >
<Columns>
<asp:BoundField DataField="Id" HeaderText="Id" />
<asp:BoundField DataField="Name" HeaderText="Name" />
<asp:BoundField DataField="Department" HeaderText="Department" />
<asp:BoundField DataField="EmailID" HeaderText="Email ID" />
<asp:BoundField DataField="Position" HeaderText="Position" />
<asp:TemplateField HeaderText="Present">
<ItemTemplate>
<asp:Button ID="Button1" runat="server" CommandArgument='<%#Eval("Id") %>' OnClick="Button1_Click" Text="Present" />
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
<asp:Label ID="Label1" runat="server" Text="Label"> </asp:Label>
</asp:Panel>
</div>
Event Method:
protected void Button1_Click(object sender, EventArgs e)
{
LinkButton lnk = (LinkButton)sender;
string id = lnk.CommandArgument.ToString();
Label1.Text = id;
}
Please be kind to help me. I'm beginner. Elaborate answer is much appreciated. Thanks for your time.
set
EnableEventValidation="false" in the page directive in code-behind
for ex:
<%# Page Language="C#" EnableEventValidation="false" AutoEventWireup="true" CodeFile="Default2.aspx.cs" Inherits="Default2" %>
EDIT: .aspx :
<asp:Button ID="Button1" runat="server"
OnClick = "Button1_Click" CommandArgument='<%#Eval("Id") %>' Text="Present" />
cs code:
protected void Button1_Click(object sender, EventArgs e)
{
Button btn = (Button)sender;
string id = btn.CommandArgument.ToString();
}
using ButtonField and an OnRowCommand Event
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns = "false"
OnRowCommand = "OnRowCommand">
<Columns>
<asp:ButtonField CommandName = "ButtonField" DataTextField = "CustomerID"
ButtonType = "Button"/>
</Columns>
</asp:GridView>
Code Behind:
protected void OnRowCommand(object sender, GridViewCommandEventArgs e)
{
int index = Convert.ToInt32(e.CommandArgument);
GridViewRow gvRow = GridView1.Rows[index];
}
How to get the AppId from gridView in codebehind, if I clicked the edit image button in second row.
Aspx Code:
<asp:BoundField HeaderText="AppId" DataField="AppID" />
<asp:TemplateField HeaderText="Actions" ControlStyle-Width="20px" ItemStyle-Width="130px">
<ItemTemplate>
<asp:ImageButton ID="imgMailCamp" runat="server" ImageUrl="~/Images/AppSetup/Mail.png"
Height="18px" ToolTip="Send Mail Campaign" CssClass="grdImageAlign" CommandName="SendMail" OnClick="btnMailCamp_Click" />
<asp:ImageButton ID="imgViewApp" runat="server" ImageUrl="~/Images/AppSetup/application-view-list-icon.png"
Height="18px" ToolTip="View Appplication" CssClass="grdImageAlign" CommandName="View" OnClick="btnView_Click" />
<asp:ImageButton ID="imgEditApp" runat="server" ImageUrl="~/Images/AppSetup/Action-edit-icon.png"
Height="18px" ToolTip="Edit Application" CssClass="grdImageAlign" CommandName="Edit" OnClick="btnEdit_Click"/>
<asp:ImageButton ID="imgDeleteApp" runat="server" ImageUrl="~/Images/AppSetup/Trash-can-icon.png"
Height="18px" ToolTip="Delete Application" CssClass="grdImageAlign" CommandName="Delete" OnClick="btnDelete_Click" />
</ItemTemplate>
</asp:TemplateField>
C# Code:
protected void btnEdit_Click(object sender, EventArgs e)
{
// I need to get the current row appId, I use this appId in next page for sql query
Response.Redirect("/Secured/EditApplication.aspx?AppID="+AppID);
}
Try Like this....Don't Define Click Event of Button....Define Button Like this...
<asp:ImageButton ID="imgEditApp" runat="server"
ImageUrl="~/Images/AppSetup/Action-edit-icon.png"
Height="18px" ToolTip="Edit Application" CssClass="grdImageAlign"
CommandName="Edit"/>
And
Define Your GridView RowEditing event Like this....
protected void gv_RowEditing(object sender, GridViewEditEventArgs e)
{
Response.Redirect("/Secured/EditApplication.aspx?AppID="+YourGridViewId.Rows[e.NewEditIndex].Cells[1].Text);
}
Edit:
I think you have problem in definig RowEditingEvent.....ok you can do this...nothing to change just write this code in you Click event...
protected void btnEdit_Click(object sender, EventArgs e)
{
ImageButton ib = sender as ImageButton;
GridViewRow row = ib.NamingContainer as GridViewRow;
Response.Redirect("/Secured/EditApplication.aspx?AppID="+YourGridViewId.Rows[row.RowIndex].Cells[1].Text);
}
Edit 2
<asp:ImageButton ID="imgEditApp" runat="server"
ImageUrl="~/Images/AppSetup/Action-edit-icon.png"
Height="18px" ToolTip="Edit Application" CssClass="grdImageAlign"
CommandName="Edit" CommandArgument='<%#Eval("AppID") %>'/>
protected void btnEdit_Click(object sender, EventArgs e)
{
string appid= (sender as ImageButton).CommandArgument;
Response.Redirect("/Secured/EditApplication.aspx?AppID="+appid
}
You can get grid view cell value from this.
GridView.Rows[RowIndex].Cells[CellIndex].Text
Here "RowIndex" is row number from which you want to get data and "CellIndex" is cell number from which you want to get data.
I think event "OnRowCommand" of gridview is best suited for your problem.
use blow link for more details
http://www.codeproject.com/Tips/564619/Example-of-gridview-rowcommand-on-Button-Click
it should be with commandargument
aspx
<asp:ImageButton ID="imgEditApp" CommandArgument='<%# Eval("AppID") %>' runat="server" ... OnClick="btnEdit_Click"/>
code
protected void gv_RowEditing(object sender, GridViewEditEventArgs e)
{
int categoryId = Convert.ToInt32(e.CommandArgument);
Response.Redirect("/Secured/EditApplication.aspx?AppID="+categoryId);
}
or u can use PostBackUrl property of imagebutton and it would be like this:
<asp:ImageButton ID="imgEditApp" PostBackUrl='<%# string.Format("/Secured/EditApplication.aspx?AppID={0}", Eval("AppID")) %>' runat="server" />
Check this code snippet.
This is the code in aspx file having two columns DataBound "AppId" and TemplateColumn "Action" containing Image Button. Observe CommandName and CommandArgument properties of Image Button. Also Define OnRowCommand Event listener for gridview.
<asp:GridView ID="grdDisplayData" runat="server" AutoGenerateColumns="false"
EnableViewState="false" onrowcommand="grdDisplayData_RowCommand">
<Columns>
<asp:BoundField HeaderText="AppId" DataField="AppId" />
<asp:TemplateField HeaderText="Action" >
<ItemTemplate>
<asp:Button ID="btnEdit" runat="server" Text="Edit" CommandName="MyEdit"
CommandArgument="<%# ((GridViewRow) Container).RowIndex%>"/>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="ImageAction">
<ItemTemplate>
<asp:ImageButton ID="ImageButton1" runat="server" Width="15px" Height="15px"
CommandName="ImgEdit" CommandArgument="<%# ((GridViewRow) Container).RowIndex%>"/>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
And here is the code behind code. The e.CommandArument returns the index of the row in which the image button was clicked.
protected void grdDisplayData_RowCommand(object sender, System.Web.UI.WebControls.GridViewCommandEventArgs e)
{
if (e.CommandName == "ImgEdit")
{
int RowIndex = Convert.ToInt32(e.CommandArgument);
Response.Redirect("/Secured/EditApplication.aspx?AppID=" + grdDisplayData.Rows[RowIndex].Cells[1].Text.Trim());
}
}
Let me know if this fixed your problem.
Cheers!!!
Piyush Deshpande
I need to add a column with a file upload control to my grid view so that I can upload files against any particular row. Is it possible to do this, ideally I need to be able to do this without putting the gridview into it's edit state.
You can use this within the as follows:
<asp:TemplateField HeaderText="UploadImage">
<ItemTemplate>
<asp:Image ImageUrl="~/images/1.jpg" runat="server" ID="image" /> // shown only when not in edit mode
</ItemTemplate>
<EditItemTemplate>
<asp:FileUpload ID="FileUpload1" runat="server" /> // shown only in edit mode
</EditItemTemplate>
</asp:TemplateField>
At last include a as follows to enter edit mode.
<asp:commandField showEditButton="true" showCancelButton="true">
Then add two events as follows:
protected void GridView1_RowEditing(object sender, GridViewUpdateEventArgs e)
{
gvwID.EditIndex=e.NewEditIndex;
BindGrid();
}
protected void GridView1_RowCancelEdit(object sender, GridViewUpdateEventArgs e)
{
gvwID.EditIndex=-1;
BindGrid();
}
The FileUpload control, will not automatically save the uploaded file. To save the file you need to use the FileUpload control’s SaveAs method. Before you can use the SaveAs method you need to get the instance of the FileUpload control for the row you are editing. To get the instance of the control you can hook up to the GridView’s RowUpdating event. The following code will get the instance of the FileUpload control and save the uploaded file:
protected void GridView1_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
int RowID=Convert.ToInt32(gvwID.DataKeys[e.RowIndex].value);
FileUpload fileUpload = GridView1.Rows[e.RowIndex].FindControl("FileUpload1") as FileUpload;
if(fileUpload.HasFile)
{
fileUpload.SaveAs(System.IO.Path.Combine(Server.MapPath("Images"), fileUpload.FileName));
//update db using the name of the file corresponding to RowID
}
gvwID.EditIndex=-1;
BindGrid();
}
Hope this will help...
The following link will help you:
http://msdn.microsoft.com/en-us/library/7tas5c80.aspx
It has a sample code for adding a DateTimePicker to datagridview cell.
You may add the fileupload control the same way...
Hope this helps...
Sudha have a great post with full functionality of file upload in GridView:
Fileupload control in gridview?
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" DataKeyNames="ID"
DataSourceID="AccessDataSource1" Width="148px" OnRowCommand="GridView1_RowCommand">
<Columns>
<asp:BoundField DataField="ID" HeaderText="ID" ReadOnly="True" SortExpression="ID" />
<asp:BoundField DataField="Name" HeaderText="Name" SortExpression="Name" />
<asp:TemplateField>
<ItemTemplate>
<asp:Label ID="lblFileUpLoad" runat="server"></asp:Label>
</ItemTemplate>
<EditItemTemplate>
<asp:FileUpload ID="FileUpload1" runat="server" />
</EditItemTemplate>
</asp:TemplateField>
<asp:CommandField ShowEditButton="true" ShowDeleteButton="true" />
</Columns>
</asp:GridView>
....
The EditTemplate looks like this:
<EditItemTemplate>
<asp:TextBox ID="txtImage" runat="server" Text='<%# Bind("Image") %>' Visible="False"></asp:TextBox>
<asp:FileUpload ID="FileUpload1" runat="server" />
</EditItemTemplate>
In code behind this will upload the file on Row Update:
protected void GridView1_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
GridViewRow row = GridView1.Rows[e.RowIndex] as GridViewRow;
FileUpload FileUpload1 = (FileUpload)GridView1.Rows[e.RowIndex].FindControl("FileUpload1");
if (FileUpload1 != null && FileUpload1.HasFile)
{
FileUpload1.SaveAs(Server.MapPath("~/uploads/" + myfilename));
}
}
This check is in place in case no file is selected so previous name is picked. Note in edit template we have placed a textbox that has visibility set to false which binds to the image name in the DB
protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
{
if (GridView1.EditIndex == -1) return;
FileUpload fileUpLoad = GridView1.Rows[GridView1.EditIndex].FindControl("FileUpload1") as FileUpload;
string fileName = fileUpLoad.FileName;
TextBox txtImage = GridView1.Rows[GridView1.EditIndex].FindControl("txtImage") as TextBox;
if (fileUpLoad != null && fileUpLoad.HasFile)
{
txtImage.Text = fileUpLoad.FileName;
}
else
{
txtImage.Text = txtImage.Text;
}
}
<asp:ScriptManager runat="server" ID="scm"></asp:ScriptManager>
<asp:UpdatePanel runat="server" ID="upMain" UpdateMode="Conditional">
<ContentTemplate>
<asp:GridView AutoGenerateColumns="False" runat="server" ID="dt">
<Columns>
<asp:TemplateField HeaderText="Catagory">
<ItemTemplate>
<asp:DropDownList runat="server" ID="ddlSubCat">
</asp:DropDownList>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Attachments">
<ItemTemplate>
<asp:UpdatePanel runat="server" UpdateMode="Conditional" ID="updFU"> <ContentTemplate>
<asp:FileUpload runat="server" ID="updCon" /><asp:Button runat="server" ID="btnUpload" Text="Upload" />
</ContentTemplate>
<Triggers>
<asp:PostBackTrigger ControlID="btnUpload" />
</Triggers>
</asp:UpdatePanel>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
</ContentTemplate>
</asp:UpdatePanel>