How to use button in repeater control? - c#

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

Related

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

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 !

working of linkbutton in repeater

I used a linkbutton in repeater which on click shows data in a label.Now i want that clicking again the same linkbutton hide that data,means same button for showing and hiding data.
there is a database with a table which contains ques-description,date,sub. by and ans.
On page load only question appears.
Now this is the design code:
protected void Repeater1_ItemCommand(object source, RepeaterCommandEventArgs e)
{
if (e.CommandName == "showanswers")
{
Control control;
control = e.Item.FindControl("date");
if(control!=null)
control.Visible = true;
control = e.Item.FindControl("subby");
if(control!=null)
control.Visible = true;
control = e.Item.FindControl("ans");
if(control!=null)
control.Visible = true;
}
And this is the html code i used:
<asp:Repeater ID="Repeater1" runat="server"
onitemcommand="Repeater1_ItemCommand">
<ItemTemplate>
<table>
<b>Question<%#Container.ItemIndex + 1%>:</b><%#Eval("qstdsc") %><br />
<asp:linkbutton ID="Button1" Text="Ans." commandname="showanswers" runat ="server" /><br />
</table>
<table>
<asp:Label id="date" Text='<%# Eval("qstdat")%>' Visible="false" runat="server"/>
</table>
<table>
<asp:Label id="subby" runat="server" Text='<%# Eval("qstsubby")%>' Visible="false" />
</table>
<table>
<asp:Label id="ans" runat="server" Text='<%# Eval("qstans")%>' Visible="false" />
</table>
</ItemTemplate>
</asp:Repeater>
But i don't know how to hide data again clicking the same linkbutton.
Is it possible with a single button?
What hinders you to check if the label is visible and hide/show it accordingly?
protected void lnkBtnShowDataLabel_Click(Object sender, EventArgs e)
{
lblData.Visible = !lblData.Visible;
}

DefaultButton in Repeater with textbox and button?

I have a repeater, which represents a shoppingbasket. This shopping basket has an "Update quantity" and a "Delete item" button.
When you edit the quantity and click enter, I will need it to use the Update quantity button (unlike now where it uses the delete item button).
In the code I've tried fixing this by adding a "QuantityPanel" with a DefaultButton, but this doesn't solve my issue!
Any ideas?
My code:
<asp:Repeater ID="ProductBasketRepeater" runat="server"
onitemcommand="ProductBasketRepeater_ItemCommand"
onitemdatabound="ProductBasketRepeater_ItemDataBound1">
<ItemTemplate>
<tr class="BasketEntryItem">
<td class="ImageCol">
<asp:Image ID="ProductImageBox" runat="server" Width="50" />
</td>
<td class="NameCol">
<asp:HyperLink ID="ProductNameHyperlink" runat="server"></asp:HyperLink>
</td>
<td class="PriceCol">
<asp:Label ID="PriceLabel" runat="server"></asp:Label>
</td>
<td class="QuanCol">
<asp:Panel ID="QuantityPanel" runat="server" DefaultButton="UpdateQuantityBtn">
<asp:TextBox ID="QuantityBox" runat="server" Width="30px"></asp:TextBox>
<asp:LinkButton ID="UpdateQuantityBtn" runat="server" Text="Opdater" CommandName="UpdateQuantity"></asp:LinkButton>
</asp:Panel>
</td>
<td class="TotalCol">
<asp:Label ID="TotalPriceLabel" runat="server"></asp:Label><br />
<asp:Button ID="DeleteProductBtn" runat="server" Text="Slet" CommandName="Delete" />
</td>
</tr>
</ItemTemplate>
<SeparatorTemplate>
</SeparatorTemplate>
</asp:Repeater>
In case jQuery is unavailable, you can use simple JavaScript to set to set default button for any texbox:
JS Code:
function clickButton(e, buttonid){
var evt = e ? e : window.event;
var bt = document.getElementById(buttonid);
if (bt){
if (evt.keyCode == 13){
bt.click();
return false;
}
}
}
ASPX page or any simple "input" textbox:
<input name="TextBox1" type="text" id="TextBox1" onkeypress="return clickButton(event,'Button1')" />
Code begind C#:
TextBox1.Attributes.Add("onkeypress", "return clickButton(event,'" + Button1.ClientID + "')");
Do you need help with apply this code in repeater ?
Using jQuery, this piece of code will issue a programmatic click when pressing enter in the textbox:
$('input[id$=QuantityBox]').keypress(function(e) {
if (e.keyCode == 13) {
$(this).next('input[id$=UpdateQuantityBtn]').click();
}
});
Note: I saw a bit late you did not requested jquery specifically, but in you do, this should do the trick.

How to get the clientid of the control which is placed inside the Edit item template of the gridview in javascript

i to get the clientid of the control which is placed inside the Edit item template of the gridview in javascript without going to the server side code..
<asp:TemplateField HeaderText="FromDate" SortExpression="FromDate">
<ItemTemplate>
<asp:Label ID="FromDate" runat="server" Text='<%#((DateTime)DataBinder.Eval(Container.DataItem,"FromDate")).ToShortDateString()%>'></asp:Label>
<asp:HiddenField ID="ID" runat="server" Value='<%#Eval("ID") %>' />
<asp:HiddenField ID="ApproveLeaveID" runat="server" Value='<%#Eval("ApproveLeaveID") %>' />
<asp:HiddenField ID="hidLevel3" runat="server" Value='<%#Eval("Level3ManagerACENumber") %>' />
</ItemTemplate>
<EditItemTemplate>
<table>
<tr>
<td>
<asp:TextBox ID="txtFDate" runat="server" Text='<%#((DateTime)DataBinder.Eval(Container.DataItem,"FromDate")).ToShortDateString()%>'>
</asp:TextBox>
<asp:HiddenField ID="ID" runat="server" Value='<%#Eval("ID") %>' />
<asp:HiddenField ID="ApproveLeaveID" runat="server" Value='<%#Eval("ApproveLeaveID") %>' />
<asp:HiddenField ID="hidLevel3" runat="server" Value='<%#Eval("Level3ManagerACENumber") %>' />
</td>
<td>
<a onclick="showCalendarControl(3,<%# Container.ItemIndex %>)">
<img id="img3" runat="server" alt="Clock" src="../Images/clock_add.png" style="border: none" /></a>
</td>
</tr>
</table>
</EditItemTemplate>
<ItemStyle HorizontalAlign="Left" />
<HeaderStyle HorizontalAlign="Center" />
</asp:TemplateField>
<asp:TemplateField HeaderText="ToDate" SortExpression="ToDate">
<ItemTemplate>
<asp:Label ID="ToDate" runat="server" Text='<%#((DateTime)DataBinder.Eval(Container.DataItem,"ToDate")).ToShortDateString()%>'>'></asp:Label>
</ItemTemplate>
<EditItemTemplate>
<table>
<tr>
<td>
<asp:TextBox ID="txtTDate" runat="server" Text='<%#((DateTime)DataBinder.Eval(Container.DataItem,"ToDate")).ToShortDateString()%>'>
</asp:TextBox>
</td>
<td>
<a onclick="showCalendarControl(4,<%# Container.ItemIndex %>)">
<img id="img4" runat="server" alt="Clock" src="../Images/clock_add.png" style="border: none" /></a>
</td>
</tr>
</table>
</EditItemTemplate>
<ItemStyle HorizontalAlign="Left" />
<HeaderStyle HorizontalAlign="Center" />
</asp:TemplateField>
This is my java script:
function showCalendarControl(ControlNo,index) {
var textField;
if(ControlNo==1)
{
textField=document.getElementById('<%=txtFromDate.ClientID%>');
}
else
{
textField=document.getElementById('<%=txtToDate.ClientID%>');
}
if(ControlNo==3)
{
textField=document.getElementsByClassName('txtFDate')[index];
}
if(ControlNo==4)
{
textField=document.getElementsByClassName('txtTDate')[index];
}
calendarControl.show(textField);
}
first two textbox(txtFromDate,txtToDate) is for the not in the grid control...
You can fetch the elements in the ItemDataBound event of the grid (using FindControl), and then pass the ClientID of the textbox as a parameter to showCalendarControl:
TextBox txtFDate = e.Item.FindControl("txtFDate") as TextBox;
TextBox txtTDate = e.Item.FindControl("txtTDate") as TextBox;
HtmlAnchor link = e.Item.FindControl("aLink") as HtmlAnchor;
if (txtTDate != null && txtFDate != null && link != null)
{
link.Attributes.Add("onclick", String.Format("showCalendarControl({0}, '{1}', '{2}')", 4, txtFDate.ClientID, txtTDate.ClientID);
}
(you'll also need to add an ID and a runat="server" to your link. I'm also assuming txtFDate is declared in your EditTemplate although it's not there. The ControlNo parameter could be a data key instead of a constant as in the example, it's not really clear what it is)
Then, in your function, use the clientID parameters to get the textboxes:
function showCalendarControl(ControlNo, txtFDateClientID, txtTDateClientID) {
var textField;
if(ControlNo==3)
{
textField=document.getElementById(txtFDateClientID);
}
if(ControlNo==4)
{
textField=document.getElementById(txtTDateClientID);
}
calendarControl.show(textField);
}
The problem is that every control should have unique server ID. So server side controls which are placed inside template are rendered multiple times with different auto generated ids based on ID you've specified in the template. You can easily see it if you will have a look on the generated html. Therefore your js code is accessing only the html element with hardcoded id. As I guess it is placed in the first row.
Simple solution is to describe your text box in a following way
<asp:TextBox ID="txtTDate" runat="server" CssClass="txtTDate" Text='<%#((DateTime)DataBinder.Eval(Container.DataItem,"ToDate")).ToShortDateString()%>'>
</asp:TextBox>
Then modify the js function in the following way :
function showCalendarControl(ControlNo, index) {
var textField;
if(ControlNo==3)
{
textField=document.getElementsByClassName('txtFDate')[index];
}
if(ControlNo==4)
{
textField=document.getElementsByClassName('txtTDate')[index];
}
calendarControl.show(textField);
}
And modify your link as the following :
<a onclick="showCalendarControl(4, <%# Container.DataItemIndex %>)">
Updated the answer
DataItemContainer has DataItemIndex property which has to be used in this case.

Adding javascript to a link's OnClientClick property while binding a repeater

I'm trying to get this working but no success:
<asp:Repeater ID="Repeater1" runat="server" OnItemCommand="btnDeleteFamily_Click">
<HeaderTemplate>
<table>
<tr>
<th width="90" valign="top"><%=getTag("name")%></th>
</tr>
</HeaderTemplate>
<ItemTemplate>
<tr>
<td><%#Eval("chrname")%></td>
<asp:LinkButton ID="btnDeleteFamily" CssClass="fRight ui-icon ui-icon-trash" runat="server" CommandName="delete" CommandArgument='<%#Eval("idmember")%>' OnClientClick='return confirm("<%= getTag("deletefamilymemberdialog") %>")' Text="" ValidationGroup="delete_family" />
</td>
</tr>
</ItemTemplate>
<FooterTemplate>
</table>
</FooterTemplate>
</asp:Repeater>
When clicking on the btnDeleteFamily OnClientClick the confirm dialog is not shown.
getTag (method in the code behind) is used for localization to get the text depending on the language. My intention is to show that message in the JavaScript dialog, but I'm getting:
<a href="javascript:__doPostBack('ctl00$ContentPlaceHolder1$rptFamily$ctl01$btnDeleteFamily','')" class="fRight ui-icon ui-icon-trash" id="ctl00_ContentPlaceHolder1_rptFamily_ctl01_btnDeleteFamily" onclick='return confirm("<%= getTag("deletefamilymemberdialog") %>");'/>
So it's not processing getTag in the server side otherwise I would be getting
onclick='return confirm("Are you sure that you want to delete this entry?");'
Thanks
I think writing the message to page as a javascript variable is a better solution :
<script>
var deleteMemberDialogMessage = '<%= getTag("deletefamilymemberdialog") %>';
</script>
And your repeater :
<asp:LinkButton ID="btnDeleteFamily" CssClass="fRight ui-icon ui-icon-trash"
runat="server" CommandName="delete" CommandArgument='<%#Eval("idmember")%>'
OnClientClick='return confirm(deleteMemberDialogMessage)' Text=""
ValidationGroup="delete_family" />
By the way be sure that your deletefamilymemberdialog message doesn't have single quote.
EDIT : If you want to bind a value from your datasource to your repeater, you should bind your column to control instead of Response.Write (<%=) like that :
<asp:LinkButton ID="btnDeleteFamily" CssClass="fRight ui-icon ui-icon-trash"
runat="server" CommandName="delete" CommandArgument='<%#Eval("idmember")%>'
OnClientClick='<%# Bind("return confirm('{0}');'", "YourColumnName") %> Text=""
ValidationGroup="delete_family" />
protected void Repeater_ItemDataBound(object sender, RepeaterItemEventArgs e)
{
LinkButton lb = e.Item.FindControl("btnDelete") as LinkButton;
if (lb != mull) {
lb.OnClientClick = "whatever";
}
}
It seems to be ok, for me at least.
You could try it in firefox, and using the WebDeveloper toolbar or Firebug extensions you will be able to get more information about what is happening behind scene.
Maybe there are others errors on the page that doesn't allow this code to work.
If you want to use the jQuery dialog in confirmation mode to bind to link buttons on a repeater inside an update panel, AND the code you want to execute after confirmation is different for each row, you can set it up this way:
Add a javascript function to your page/control like this:
function confirm(buttonFunctionForPostBack)
{
$("#dialog").dialog('option', 'buttons', {
"Cancel": function() {
$(this).dialog("close");
},
"Delete Payment": function () {
eval(buttonFunctionForPostBack);
$(this).dialog("close");
}
}
).dialog('open');
}
And in your code behind:
public void Repeater1_ItemDataBound(object sender, RepeaterItemEventArgs e)
{
LinkButton lb = e.Item.FindControl("deleteButton") as LinkButton;
if (lb != null)
{
lb.OnClientClick = "confirm(\"" + this.Page.ClientScript.GetPostBackEventReference(lb, string.Empty) + "\");return false;";
}
}
And in your aspx page:
<asp:Repeater ID="Repeater1" runat="server" OnItemDataBound="Repeater1_ItemDataBound">
<HeaderTemplate>
<table>
<tr>
<th width="90" valign="top"></th>
</tr>
</HeaderTemplate>
<ItemTemplate>
<tr>
<td><%#Eval("name")%></td>
<td><asp:LinkButton ID="deleteButton" runat="server" CommandName="delete" CommandArgument='<%#Eval("id")%>' Text="Delete" />
</td>
</tr>
</ItemTemplate>
<FooterTemplate>
</table>
</FooterTemplate>
</asp:Repeater>
This lets you take advantage of the fact that you can set the dialog's 'buttons' option after the dialog was created. Also, it doesn't require any extra script variables.

Categories

Resources