GridView Value Pass - c#

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];
}

Related

How to get cell value in a GridView on LinkButton Click Event? Or RowCommand?

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;
}

Hide Column In Grid

This is my html mark-up and adding the visibility to false in the div tag hides the actual data itself, but just leaves a blank column. I tried to access the div tag (yes I added the runat="server" tag to the html) and attempted to access it like so hideme.Visible = true; which threw a compile error of
Does not exist in the current context.
What should I alter/modify to ensure that this column is completely hidden from my grid?
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" ShowFooter="true"
onrowdatabound="GridView1_RowDataBound" onrowcreated="GridView1_RowCreated">
<Columns>
<asp:BoundField DataField="abcd" HeaderText="abcd" />
<asp:BoundField DataField="def" HeaderText="def" />
<asp:BoundField DataField="hij" HeaderText="hij" />
<asp:BoundField DataField="xyz" HeaderText="xyz" />
<asp:BoundField DataField="eee" HeaderText="eee" />
<asp:BoundField DataField="era" HeaderText="era" />
<asp:BoundField DataField="nai" HeaderText="nai" />
<asp:BoundField DataField="fac" HeaderText="fac" />
<asp:TemplateField>
<ItemTemplate>
<div runat="server" style="visibility:hidden" id="hideme">
<asp:Label ID="lbllunch" runat="server" Text='<%# Eval("hij") %>' />
<asp:Label ID="lbllunchoverage" runat="server" Text='<%# Eval("xyz") %>' />
<asp:Label ID="lbleee" runat="server" Text='<%# Eval("eee") %>' />
<asp:Label ID="lblera" runat="server" Text='<%# Eval("era") %>' />
<asp:Label ID="lblnai" runat="server" Text='<%# Eval("nai") %>' />
<asp:Label ID="lblfac" runat="server" Text='<%# Eval("fac") %>' />
</div>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
EDIT
I added the .Visible command to my page load event (where I always hide anything on my page) like so:
protected void Page_Load(object sender, EventArgs e)
{
hideme.Visible = false;
/More here
}
Since hideme is inside the GridView TemplateField, you can't access it in Page_Load method, however you can access it in GridView1_RowDataBound method as below
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
// find the hideme div
HtmlGenericControl div = (HtmlGenericControl)e.Row.FindControl("hideme");
// set the visible property
div.Visible = false;
}
}
You can hide the column in DataBound event of gridview.
protected void GridView_DataBound(object sender, GridViewRowEventArgs e)
{
GridView.Columns[8].Visible = false;
}
If you want to hide template field column why you are adding it to markup. Yes if you keep style="visibility:hidden" it will show blank column only because item template still exists as column.
My suggestion for you is if dont need column dnt add markup.

How to get gridview column value in codebehind

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

Gridview: Index was out of range

I have 3 GridView controls in 3 different pages.They worked fine before.
Suddenly I got this error message:
Invalid postback or callback argument. Event validation is enabled using <pages enableeventvalidation="true" />
So I tried to put <#pages enableeventvalidation="false" /> in the page. It still did not work.
I deleted this command from page. Then another message shows up " Index was out of range" when click the buttons in the gridview for all the girdview controls.
int id = Convert.ToInt32(myGridView.DataKeys[e.RowIndex].Value)
It looks like the gridview could not find the datakey (e.rowIndex's value is OK), Datakeynames has been set.
protected void gvItemCategory_RowDeleting(object sender, GridViewDeleteEventArgs e) {
int categoryId = Convert.ToInt32(gvItemCategory.DataKeys[e.RowIndex].Value);
CollectionCategory category = new CollectionCategory();
category.CategoryId = categoryId;
category.Delete();
ItemCateogryShowData();
}
HTML:
<asp:GridView ID="gvItemCategory" runat="server" AutoGenerateColumns="False"
OnRowCancelingEdit="gvItemCategory_RowCancelingEdit"
OnRowDeleting="gvItemCategory_RowDeleting" OnRowEditing="gvItemCategory_RowEditing"
DataKeyNames="CategoryId" OnRowUpdating="gvItemCategory_RowUpdating">
<Columns>
<asp:TemplateField HeaderText="CateogoryName">
<ItemTemplate>
<asp:Label ID="lblItemCategoryName" runat="server" Text='<%#Eval("CategoryName") %>'></asp:Label>
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="tbItemCateogryName" runat="server" Text='<%#Eval("CategoryName") %>'></asp:TextBox>
</EditItemTemplate>
</asp:TemplateField>
<asp:CommandField ShowEditButton="True" ButtonType="Button" />
<asp:CommandField ShowDeleteButton="True" />
</Columns>
</asp:GridView>
Try binding your Gridview on pageload !ispostback method..
If(!isPostback)
{
//your code here
}
Try this
int categoryId = Convert.ToInt32(gvItemCategory.DataKeys[e.RowIndex].Value.Tostring());
NOTE:Also use EnableeventValidation="false"

functions in update panel

<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?

Categories

Resources