Get Column value 'TemplateField' of Each row in Button Click event - c#

I have created a gridview using TemplateField. And Added Add Button And this redirects to other page and i want to get the one column value of row.
Here is the code -
<Columns>
<asp:TemplateField HeaderText="Accession ID">
<ItemTemplate>
<asp:Label Text='<%# Eval("AccessionID") %>' runat="server"></asp:Label>
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="txtFirstName" Text="Hello" runat="server" />
</EditItemTemplate>
<FooterTemplate>
<asp:TextBox ID="txtFirstNameFooter" runat="server" />
</FooterTemplate>
</asp:TemplateField>
......
<asp:TemplateField HeaderText="Add Container">
<ItemTemplate>
<asp:Button ID="btnAddContainer" runat="server" CommandName="" Text="Add Container" CommandArgument='<%# Eval("AccessionID") %>' OnClick="ContainerforAccession" class="btn btn-primary btn-md" />
</ItemTemplate>
</asp:TemplateField>
CS Code -
protected void ContainerforAccession(object sender, EventArgs e)
{
Button btn = (Button)sender;
GridViewRow row = (GridViewRow)btn.NamingContainer;
}
I have this code with me. I want to get first column value (AccessionID) in my case in every button click of the Grid.
I have tried across multiple solutions. But unfortunately, we have the answers for 'asp:BoundField' Implementation. I am looking for 'asp:TemplateField'
Please let me know if i need to convert to asp:BoundField. If so, How can the above design can be changed - Binding Text='<%# Eval("AccessionID") %> to Textbox.
Thanks in advance. Looking for a solution.

Change the OnClick of the button to OnCommand. Then you have access to the CommandEventArgs.
<asp:Button ID="btnAddContainer" OnCommand="ContainerforAccession"
protected void ContainerforAccession(object sender, CommandEventArgs e)
{
string AccessionID = e.CommandArgument.ToString();
}

Changed All the Template fields to Bound-Fields and in cs code -
int AccessionID = Int32.Parse((sender as Button).CommandArgument);
Solved my issue !

Related

How Do I Transfer Grid view values to next page

How Do I Transfer Grid view values to next page. Grid view consist one of the text box(txtItemGroup) which values have to be entered by the user dynamically, not from the Data base.
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="false" HorizontalAlign="Center">
<Columns>
<asp:TemplateField HeaderText="Item Name">
<ItemTemplate>
<asp:Label ID="lblName" runat="server" Text='<%# Eval("TestItemName") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Items Group">
<ItemTemplate>
<asp:Label ID="lblGroup" runat="server" Text='<%# Eval("TestItemGroup") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Group">
<ItemTemplate>
<asp:TextBox ID="txtItemGroup" runat="server"></asp:TextBox>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Item Values">
<ItemTemplate>
<asp:Label ID="lblItemValue" runat="server" Text='<%# Eval("TestItemValues") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Default Values">
<ItemTemplate>
<asp:Label ID="lblDefaultValues" runat="server" Text='<%# Eval("DefaultValues") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
In your GridView's RowCommand event put in the following code:
if (e.CommandName == "Send")
{
TextBox txt = (TextBox)GridView1.FindControls("txtItemGroup");
Session["ItemGroup"] = txt.Text;
}
In addition to this, put a Button or LinkButton in your GridView's ItemTemplate to send the value of the appropriate Textbox as you have put a TextBox and set it's CommandName property in the .aspx page as:
<asp:Button id="btnSend" runat="server" Text = ">" commandName="Send"/>
And then in the Page_Load event of the page where you want the value of TextBox to be viewed:
if (!IsPostback)
{
Label1.Text = Session["ItemGroup"].ToString();
//or
Label1.Text = (String)Session["ItemGroup"];
}
try this:-
Add a button just below that textbox like this:-
<asp:Button ID="btnsend" Text="Send" runat="server" CommandName="Send" />
In RowCommand event write like this:-
protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
{
if (e.CommandName == "Send")
{
GridViewRow row = (GridViewRow)((Control)e.CommandSource).NamingContainer;
TextBox TextBox1 = row.FindControl("txtItemGroup") as TextBox;
Response.Redirect("yourasppage.aspx?txt=" + TextBox1.Text);
}
}
On page load of `yourasppage.aspx' use this code
string txtval = Request.QueryString["txt"];
Hope this will help

Fire SelectionIndexChanged with AutoGenerateSelect "False"

I have a datagrid view, and I'd like to capture a datakeyname value on a selected row of a gridview. But in this scenario one of my columns (Event Title) will be a hyperlink, and when this link is clicked it will fire selectedindexchanged and capture DataKeyName which will be passed to populate a form. Here's my code. Currently my hyperlink field is not eve "clickable". Do I need to change my approach?
<asp:GridView ID="gvEventDetails" CssClass="gvEvent" runat="server" DataKeyNames="Event_ID"
AutoGenerateColumns="false" OnSelectedIndexChanged="gvEventDetails_SelectedIndexChanged" >
<Columns>
<asp:TemplateField HeaderText="Event Title">
<ItemTemplate>
<asp:HyperLink ID="HyperLink1" Text='<%# Eval("Event_Title") %>' runat="server"></asp:HyperLink>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Client Name">
<ItemTemplate>
<asp:Label ID="ClientName" runat="server" Text='<%# Eval("Name") %>'>
</asp:Label>
</ItemTemplate>
</asp:TemplateField>
The method:
protected void gvEventDetails_SelectedIndexChanged(object sender, EventArgs e)
{
string DataKey = gvEventDetails.SelectedValue.ToString();
}
Instead of a hyperlink, try a linkbutton with command name:
<asp:TemplateField>
<ItemTemplate>
<asp:LinkButton runat="server" CommandName="Select" CommandArgument='<%# Eval("Event_ID") %>' Text='<%# Eval("Event_Title") %>'
...
The rule is that posting back with common command names (Edit, Select, Delete, Cancel etc.) is correctly recognized by the event engine.
This is what I ended up doing
protected void gvEventDetails_RowCommand(object sender, GridViewCommandEventArgs e)
{
string PK = (e.CommandArgument).ToString();
}
<asp:TemplateField HeaderText="Event Title">
<ItemTemplate>
<asp:LinkButton ID="HyperLink1" runat="server" Text='<%# Eval("Event_Title") %>'
CommandArgument='<%# Eval("Event_ID") %>'
></asp:LinkButton>
</ItemTemplate>
</asp:TemplateField>

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

How to reference a linkbutton thats inside a asp:grid when its clicked

I have a ASP:grid which has a link button, i need to some how reference that on the code behind when its clicked but im struggling on the syntax
Heres my ASP:Grid i need to execute code in the code behind when that link button 'Re-Take' is pressed and also be able to know what row it was clicked on as i will need to reference the users emails and name and then send an email with the relevant information....
<asp:GridView ID="GrdViewUsers" runat="server" AutoGenerateColumns="false" GridLines="None"
EnableViewState="false" class="tablesorter">
<AlternatingRowStyle></AlternatingRowStyle>
<Columns>
<asp:TemplateField>
<ItemTemplate>
<asp:LinkButton Text="Re-Take" runat="server" ID="Edit" CommandName="Edit"></asp:LinkButton>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Full Name">
<ItemTemplate>
<asp:HyperLink ID="HyperFullName" CssClass="gvItem" runat="server" NavigateUrl='<%#Eval("UserID","/ExamPaper.aspx?uid={0}") %>'
Text='<%# DataBinder.Eval(Container,"DataItem.FullName") %>'></asp:HyperLink>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Email">
<ItemTemplate>
<asp:Label ID="lblSurname" CssClass="gvItem" runat="server" Text='<%# DataBinder.Eval(Container, "DataItem.Email") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Exam Taken">
<ItemTemplate>
<asp:Label ID="lblUsername" CssClass="gvItem" runat="server" Text='<%# DataBinder.Eval(Container, "DataItem.ExamTaken") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Date Taken">
<ItemTemplate>
<asp:Label ID="lblUsername" CssClass="gvItem" runat="server" Text='<%# DataBinder.Eval(Container, "DataItem.DateTaken") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Exam Total">
<ItemTemplate>
<asp:Label ID="lblUsername" CssClass="gvItem" runat="server" Text='<%# DataBinder.Eval(Container, "DataItem.ExamTotal") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
If someone can help me with a snippet i would highly appreciate it
You could approach this slightly different. You see, when a control is placed inside a gridview, any event raised from that control raises also the RowCommand on the GridView.
To get what you want you could then add both CommandName and CommandArgument to your LinkButton and then catch it in the GridView's RowCommand.
<asp:LinkButton id="LinkButton1" runat="server" commandName="LinkButtonClicked" commandArgument='Eval("myObjectID")' />
where myObjectID is the name of the ID column of your object you bind the grid to.
Then
void GridView1_RowCommand( object sender, GridViewCommandEventArgs e )
{
if ( e.CommandName == "LinkButtonClicked" )
{
string id = e.CommandArgument; // this is the ID of the clicked item
}
}
see: ASP.net GridView: get LinkItem's row
FindControl should work in this case.
protected void GrdViewUsers_RowDataBound(object sender, GridViewRowEventArgs e)
{
if(e.Row.RowType == DataControlRowType.DataRow)
{
HyperLink myHyperLink = e.Row.FindControl("Edit") as HyperLink;
}
}
First: You have repeating ID's in your TemplateFields like lblUsername what is not allowed since it's the same NamingContainer.
You can pass the RowIndex as CommandArgument to RowCommand:
on aspx:
<asp:TemplateField>
<ItemTemplate>
<asp:LinkButton
Text="Re-Take"
runat="server"
ID="Edit"
CommandName="Edit"
CommandArgument="<%# ((GridViewRow) Container).RowIndex %>">
</asp:LinkButton>
</ItemTemplate>
</asp:TemplateField>
Handle the GridView's RowCommand:
void GrdViewUsers_RowCommand(Object sender, GridViewCommandEventArgs e)
{
if(e.CommandName=="Edit")
{
int index = Convert.ToInt32(e.CommandArgument);
GridViewRow row = GrdViewUsers.Rows[index];
// now you can get all of your controls like:
Label lblSurname = (Label)row.FindControl("lblSurname");
String email = lblSurname.Text // you noticed that DataItem.Email is bound to lblSurname?
}
}
Suppose the grid has linkbutton on which we want to get row index
<asp:LinkButton ID="lnkbtnAdd " runat="server" CommandName="cmdAdd" ImageUrl="~/Images/add.gif" ></asp:LinkButton>
In code behind, In OnRowCreated event we attach row number of grid to each button of row to get it back when it is clicked in RowCommand event
protected void gvListing_RowCreated(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
System.Web.UI.WebControls.LinkButton lnkbtnAdd = new System.Web.UI.WebControls.LinkButton();
lnkbtnAdd = (System.Web.UI.WebControls.LinkButton)e.Row.FindControl("lnkbtnAdd");
if (lnkbtnAdd != null)
lnkbtnAdd .CommandArgument = e.Row.RowIndex.ToString();
}
}
In RowCommand event we will get back the current row index and set the selected index of the grid
protected void gvListing_RowCommand(object sender, GridViewCommandEventArgs e)
{
if (e.CommandName.ToString() == "cmdAdd")
{
int RowIndex = int.Parse(e.CommandArgument.ToString());// Current row
}
}

How to use button in repeater control?

I am using asp.net 3.5 with c#.I want to invoke button click event inside repeater control.
<asp:Repeater ID="rptFriendsList"
runat="server"
onitemcommand="rptFriendsList_ItemCommand">
<ItemTemplate>
<asp:ImageButton ID="btnSave"
runat="server"
ImageUrl="~/Contents/Images/save_button.png"
CommandName="Schedule"
UseSubmitBehavior="False" />
</ItemTemplate>
</asp:Repeater>
but when i click to a button its giving an error
"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."
my purpose is to execute some code in button click which is placed inside the repeater.Please help me to solve this issue.Thanks in advance.
UseSubmitBehavior="False" this property you have used is not present with the image button have you over ridden imagebutton class and added this property.
<asp:Repeater ID="Repeater1" runat="server" OnItemCommand="Repeater1_OnItemCommand" DataSourceID="SqlDataSource1">
<ItemTemplate>
key1:
<asp:Label ID="key1Label" runat="server" Text='<%# Eval("key1") %>'></asp:Label><br />
key2:
<asp:Label ID="key2Label" runat="server" Text='<%# Eval("key2") %>'></asp:Label><br />
key3:
<asp:Label ID="key3Label" runat="server" Text='<%# Eval("key3") %>'></asp:Label><br />
<asp:TextBox ID="col1" runat="server" Text='<%# Eval("col1") %>'></asp:TextBox>
<asp:TextBox ID="col2" runat="server" Text='<%# Eval("col2") %>'></asp:TextBox>
<br />
<asp:linkbutton ID="Linkbutton1" commandname="Update" runat="server" text="Update" CommandArgument='<%# Eval("key1") +"|"+Eval("key2")+"|"+ Eval("key3") %>' />
<asp:linkbutton ID="Linkbutton2" commandname="Cancel" runat="server" text="Cancel" />
</ItemTemplate>
protected void Repeater1_OnItemCommand(object source, RepeaterCommandEventArgs e)
{
if (e.CommandName == "Update")
{
string col1 = ((TextBox)e.Item.FindControl("col1")).Text;
string col2 = ((TextBox)e.Item.FindControl("col2")).Text;
string allKeys = Convert.ToString(e.CommandArgument);
string[] arrKeys = new string[2];
char[] splitter = { '|' };
arrKeys = allKeys.Split(splitter);
SqlDataSource1.UpdateParameters["col1"].DefaultValue = col1;
SqlDataSource1.UpdateParameters["col2"].DefaultValue = col2;
SqlDataSource1.UpdateParameters["key1"].DefaultValue = arrKeys[0];
SqlDataSource1.UpdateParameters["key2"].DefaultValue = arrKeys[1];
SqlDataSource1.UpdateParameters["key3"].DefaultValue = arrKeys[2];
SqlDataSource1.Update();
Repeater1.DataBind();
}
}
This also happens when you have assigned the datasource and data bound your repeater in the OnLoad event rather than OnInit
I have used this bellow code and runs ok
use this bellow code in .aspx page
<asp:Repeater ID="Repeater1" runat="server" OnItemCommand="Repeater1_ItemCommand">
<HeaderTemplate>
<table>
<tr>
<th>
Edit
</th>
</tr>
</table>
</HeaderTemplate>
<ItemTemplate>
<table>
<tr>
<td align="center">
<asp:LinkButton ID="LinkButton1" runat="server" CommandName="Edit">Edit</asp:LinkButton>
</td>
</tr>
</table>
</ItemTemplate>
</asp:Repeater>
Use this in .cs Make the event Repeater1_ItemCommand
protected void Repeater1_ItemCommand(object source, RepeaterCommandEventArgs e)
{
switch (e.CommandName)
{
case "Edit":
// Do some stuff when the Edit button is clicked.
break;
// Other commands here.
default:
break;
}
}
You can't use button, because button create postback on click and also itemcommand of repeater called!
But, If you want to use asp:button instead of asp:linkbutton, you have to set UseSubmitBehavior property of button to false. its means, button dont make postback.
<asp:Button ID="btnAccept" runat="server" Text="Accept All" CssClass="vb-default vb-green vb-txt-light" CommandName="Accept" CommandArgument='<%# Eval("UserID") %>' UseSubmitBehavior="false" />
Set page EnableEventValidation="false".
if you're adding items server side, try to assign unique ID to each ImageButton

Categories

Resources