Get rowindex of gridview on click of a button outside gridview - c#

In my asp.net application (v4.0), I have a grid view. I use a list object to bind data to the grid view.
In the grid view there is a cancel button. On click of the cancel button the application should pop a message to the user asking for confirmation to proceed with cancel. ie. are you sure you want to cancel the record yes/no. When the user selects yes then the particular record should be cancelled.
Now the issue is, when the user selects yes then i need to the get the index of the row for which the cancel button is clicked and i need to remove it from the list object that is used to bind the grid and rebind the gridview .
please let me know how to achieve this.
Thanks for all the reply.. im using custom pop up instead of built in 'confirm' method. The custom pop up will have 'OK' and 'Cancel' button controls. Only on click of 'OK' button i need to get the selected record index. Built in confirm method mentioned in some replies will not suit my scenario. please let me know how to achieve this.

Add a hiddenfield into your page
<asp:HiddenField ID="HiddenField1" runat="server" />
Use the Id(use corresponding column name instead of Id) of the records as the CommandArgument of Cancel button
<asp:Button ID="btncancel" runat="server" CommandArgument='<%#Eval("Id") %>' Text="Cancel" />
Then on clicking the cancel button it calls the gridviews rowcommand function. In that function keep the CommandArgument value in the hidden field as follows
protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
{
HiddenField1.Value = e.CommandArgument.ToString();
}
Then on clicking the OK button, it calls the click event. In that function remove the Item from the List and then bind the list again to the gridview
protected void btnOK_Click(object sender, ButtonClickEventArgs e)
{
string id = HiddenField1.Value;
//use this id to remove the data from the List
// bind the gridview
}

Try this..
You can use javascript function..
<asp:Button ID="Button1" runat="server" onclientclick="Validate(this) />
Declare an HTML hidden field in your page...
<input id="Hidden1" type="hidden" runat="server" clientidmode="static"/>
function Validate(obj) {
var r = confirm("are you sure you want to cancel ?");
if (r == true) {
var id = obj.id.toString();
var index = id.split("_");
var RowNumber = index[2].toString();
document.getElementById('Hidden1').value=RowNumber ;
}
else {
return;
}
}
Here we get id of the button somewhat as ContentPlacedholde_Button1_0..Then we split it to get the index..

Use command name and command argument on cancel button like this:
<asp:Button ID="btncancel" runat="server" CommandArgument='<%#Eval("Id") %>' CommandName="Cancel" Text="Cancel" />
And then on gridviewRowcommand use this:
if (e.CommandName == "Cancel")
{
int count = GridViewName.Rows.Count;
for (int i = 0; i < count; i++)
{
int id = Convert.ToInt32(e.CommandArgument);
}
}

Have you tried adding a CommandArgument value to the cancel button that represents the item, for example an ID? Then onclick, display a popup, if the user selects yes then use the ID to remove the item from your collection, then simply rebind the grid. The item will then be gone.

Related

How to determine which button was clicked in gridview

I have a gridview and my gridview has a template feild for image button,for delete one row.
At the moment I use rowcommand and rowargument for this image button to recognize what row want to delete. but I need to implement below scenario:
I want when user click on imagebutton,no postback occured ,a modal box(bootstrap modal) open ,and only when user click yesI'm sure button in modal, postback occure and data deleted...
Is this possible with asp.net gridview and if yes,How I can determine what button click in "yesI'm sure button" ???
thank you
Yes this is possible. Please try the below code:
<script type="text/javascript">
function ShowModal(gridItemIndex)
{
$(document).ready(function ()
{
$('#mymodal').modal('show');
var row = gridItemIndex.parentNode.parentNode;
var rowIndex = row.rowIndex-1; //row index of that row.
document.getElementById("<%=hfID.ClientID %>").value =rowIndex;
});
}
</script>
<asp:gridview id="yourGridView" onrowcommand="GridView_RowCommand"
<asp:TemplateField>
<ItemTemplate>
<asp:ImageButton name="btnDelete" CommandName="Delete" OnClientClick="return ShowModal(this);" ImageUrl="/imagepath.pgn" runat="server" />
</ItemTemplate>
</asp:TemplateField>
</asp:gridview>
Then in code behind use the following event of GridView.
protected void GridView_RowCommand(Object sender, GridViewCommandEventArgs e)
{
if (e.CommandName=="Delete")
{
// Write your delete code here...
}
}

How can I tell which button in a repeater got pressed?

I have the following markup in an .aspx file:
<asp:Repeater ID="ListOfAssignments" runat="server" OnItemDataBound="ListOfAssignments_ItemDataBound">
<ItemTemplate>
<asp:Label ID="AssignmentID" runat="server" Text="Label"></asp:Label>
<br />
<asp:Label ID="PathToFile" runat="server" Text="Label"></asp:Label>
<br />
<asp:Button ID="RemoveAssignment" runat="server" Text="Remove" OnClick="RemoveAssignment_Click"/>
</ItemTemplate>
</asp:Repeater>
There are two labels and a button in a fairly standard repeater control. The repeater is bound to a database, and populates the labels with records from the database.
Here's my problem: I have a click event for each button in the repeater. The RemoveAssignment_Click method is called when the user clicks any of the buttons. In the click event, I want to know the text of the two labels associated with whatever button the user clicked.
What I mean is, in this method:
protected void RemoveAssignment_Click(object sender, EventArgs e)
{
//code goes here
}
I want to be able to know the text of the labels that are adjacent to the button that was clicked. How do I do that?
What you are looking for is the Button.OnCommand Method:
This allows you to create multiple Button controls on a Web page and
programmatically determine which Button control is clicked.
So inside ListOfAssignments_ItemDataBound you'd assign the CommandArgument to the button, where the CommandArgument is the ID of the article to be deleted:
protected void ListOfAssignments_ItemDataBound(object sender, RepeaterItemEventArgs e)
{
if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem)
{
Button delButton = e.Item.FindControl("RemoveAssignment") as Button;
delButton.CommandArgument = //set to the value of AssignmentID
//rest of your code
}
}
And now your button should say to use your new OnCommand:
<asp:Button ID="RemoveAssignment" OnCommand="RemoveAssignment" runat="server" Text="Remove" />
And then you create the method:
protected void RemoveAssignment(object sender, CommandEventArgs e)
{
int articleIDToDelete = 0;
if (Int32.TryParse((string)e.CommandArgument, out articleIDToDelete))
{
//delete the article with an ID = articleIDToDelete
}
}
You can add CommandName and CommandArgument attributes to the button tag and use them as a hint. And then in your even handler you can do e.CommandName == "xxx" or e.CommandArgument == "xxx". You can also use CommandArgument to pass the actual strings. You just need to bind the data just like you would do with a label, text, etc:
<asp:Button ID="RemoveAssignment" runat="server" CommandArgument='<%#Eval("Label1")+","+ Eval("Label2")%>' Text="Remove" OnClick="RemoveAssignment_Click"/>
Then in the event handler you can do something like:
string[] args = e.CommandArgument.ToString().Split(new char[] {','});
string label1 = args[0];
string label2 = args[1];
This should get you going.
Hm, I know c# and wp but you should try to set a bool and use this logic: if it is false, repeat will continue and if it is true, it'll exit the repeat. try this:
bool exit;
void Button_Click(eventargs stuffy here)
{
exit = true,
}
void Repeat()
{
if (exit == false)
{
Repeat();
//Your code here
}
}

In ASP.NET how can I retrieve data from a specific control that is within a DataList

Within a DataList I have comments retrieved from a database. Each comment set has its own reply textbox along with a submit button to submit the reply. On the button I have an click event along with the commentID as a commandArgument so I can retrieve the comment id in my event. How do i reference the specific comment box to retrieve the text though. My comment container looks something like:
<div class="replyContainer">
<asp:TextBox ID="replyBox" runat="server"></asp:TextBox>
<asp:ImageButton ID="ImageButton1" runat="server"
CommandArgument='<%# Eval("cID") %>'
onclick="replyPostClick" />
</div>
My C# method behind looks something like:
protected void replyPostClick(object sender, EventArgs e)
{
ImageButton btn = sender as ImageButton;
CommentQueries.addComment(objectID, userID, btn.CommandArgument.ToString(), ?);
}
The question mark would be where I pass in the comment. Is there some way to retrieve the relevant textbox's text somehow?
You can get the DataListItem from the ImageButton which has been clicked.
The code would be something like;
ImageButton img = (ImageButton)sender;
DataListItem item = (DataListItem)img.NamingContainer;
// check that the item is not null
if (item != null)
{
//get the index of the Current ImageButton selected
int itemIndex = item.ItemIndex;
// find the control and value within the datalist using the itemIndex
// I don't know the ID of your DataList, so I have just called it DataList1
var replyText = ((TextBox)this.DataList1.Items[item.ItemIndex].FindControl("replyBox")).Text;
}
Once you have the item you can can then

Responding to an "enter" keypress within an <input> field

My question is about handling Enter key press.I have one page called "order.aspx" which is residing inside master page.Here i am explaining the control structure
1. <asp:TextBox ID="txtSearch" MaxLength="50" runat="server" Width="420px" CssClass="txtbox"></asp:TextBox>
2. <asp:Button ID="btnSearch" runat="server" OnClick="btnSearch_Click" />
3. one asp grid control with one column containing textbox for entering order quantity
4. <asp:Button ID="btnOrder" runat="server" OnClick="btnOrder_Click" />.
My requirement is,
while user enter text in the search textbox and press enter key then btnSearch_Click should fire
while user enter quantity in the grid textbox and press enter key then btnOrder_Click should fire.
I tried with different code finally got answers but it is not fully functional.Follwing is the javascript code i have used.
function DoEnterKeyButtonClick(buttonId) {
e = event;
var code = (e.keyCode ? e.keyCode : e.which);
if (code == 13) {
document.getElementById('ctl00_CphMaster_' + buttonId).click();
return false;
}
}
I am calling this method on key press of txtSearch and grid textbox and passing the Button id to fire event btnSearch and btnOrder respectively.When i am entering the text in the search textbox and hitting the enter key then btnSearch_Click is firing and when i am entering the order quantity and hitting the enter key the btnOrder_Click is firing.But the issue is,after changing the page index say second page the required functionality not working.That is when i am entering order quantity and hitting the enter key then btnSearch_Click will fire first , then btnOrder_Click firing.This will clear the quantity entered and results in error.Please help me...
Thanks,
Joby
Instead of giving this document.getElementById('ctl00_CphMaster_' + btnSearch).click();
Try this document.getElementById('<%= btnSearch.ClientID %>').click();
or try using jquery
$("#txtSearch").keyup(function(event){
if(event.keyCode == 13){
$("#btnSearch").click();
}
});
Else place your controls inside the asp:panel and set the DefaultButton property as btnSearch as like below
<asp:Panel ID="Panel1" runat="server" DefaultButton="btnSearch">
<asp:TextBox ID="txtSearch" MaxLength="50" runat="server" Width="420px" CssClass="txtbox"></asp:TextBox>
<asp:Button ID="btnSearch" runat="server" OnClick="btnSearch_Click" />
</asp:Panel>
Hope this will help.
Many Thanks
Anna
Your function doesn't know what exactly this even is.
Try it like this
function DoEnterKeyButtonClick(event,buttonId){}
I keep the following handy snippet around..
function getIntKey(key) {
var keycode;
if (key == null) { keycode = event.keyCode; } else { keycode = key.keyCode; }
return keycode;
}
And use it, like this..
$("#txtSearch").keyup(function(e){
if(getIntKey(e) == 13){
//Enter was pressed, do somthing
}
});

Gridview event not firing

I have a requirement where i have to update a textbox if any of the value in my grid view changes.. I have a gridview with 2 rows ..
one a template field with label and another template field with a textbox...
my Grid view looks like
name value
a (empty textbox)
b (empty textbox)
c (empty textbox)
now when the user enters a value in teh text box it should automatically update another textbox which is linked to this.
Here my questions is when someone enters a value in the textbox an event should be fired!
(I am getting the names a,b,c, from database). i dont want to have an edit link or update link because all the values to be entered are mandatory!
i tried Grid_SelectedIndexChanged1 but this not firing.. is there something i am missing or i need to change so that the evant is fired and i can update the other textbox??
I am new to ASP.NET so please help!
Thanks in advance!
If the updates are supposed to be triggered when the text changes, you should use the OnTextChanged event of the TextBox, and set AutoPostBack to true.
EDIT
To avoid duplicating efforts here, using the above approach you can find the row index using the technique that Pankaj Garg outlined in his answer:
int rowIndex = ((GridViewRow)((TextBox)sender).NamingContainer).RowIndex;
The biggest caveat to this approach is that it's not forgiving of changes in the markup. If you were to wrap the TextBox in another control that implements INamingContainer, the example above would break. For example:
<asp:TemplateField>
<asp:Panel ID="Panel1" runat="server"> <!-- becomes the naming container -->
<asp:TextBox ID="TextBox1" runat="server" onchange='valueChanged(<%# Container.ItemIndex %>);' />
</asp:Panel>
</asp:TemplateField>
That being said, you would want to notate your markup accordingly so other developers know to be careful when making changes.
EDIT
As an alternative, you could also trigger the postback in JavaScript using the onchange event of the TextBox:
<script type="text/javascript">
valueChanged = function(rowIndex){
__doPostBack("<%= GridView1.ClientID %>", rowIndex);
}
</script>
<asp:GridView ID="GridView1" runat="server" DataKeyNames="ID" ...>
<Columns>
<asp:TemplateField>
<asp:TextBox ID="TextBox1" runat="server" onchange='valueChanged(<%# Container.ItemIndex %>);' />
</asp:TemplateField>
</Columns>
</asp:GridView>
In the code-behind, override the RaisePostBackEvent method, and put your update logic there:
protected override void RaisePostBackEvent(IPostBackEventHandler source, string eventArgument)
{
base.RaisePostBackEvent(source, eventArgument);
if (source == GridView1)
{
int rowIndex = int.Parse(eventArgument);
TextBox txt = GridView1.Rows[rowIndex].FindControl("TextBox1") as TextBox;
if (txt != null)
{
var id = (int)GridView1.DataKeys[rowIndex]["ID"];
var text = txt.Text.Trim();
//update the database
}
}
}
You can check the Current Row Index like below...
((GridViewRow)((TextBox)sender).NamingContainer).RowIndex
Create a handler for OnTextChanged event and set the AutoPostBack Property True.
protected void TextBox_TextChanged(object sender, EventArgs e)
{
int CurrentGridIndex = ((GridViewRow)((TextBox)sender).NamingContainer).RowIndex
}

Categories