Making entire row in Gridview clickable - asp.net

I've been trying to follow this answer: How to implement full row selecting in GridView without select button?
But I'm still slightly confused. After following that question, my rows are now clickable. But how do I implement it to do something after being clicked? Currently, I use a button to do what I need to the database per row:
Here is the .aspx code:
<Columns>
<asp:ButtonField Text = "Click Me" CommandName = "Clicked" ButtonType = "Button" />
...other columns stuff
</Columns>
C# code behind:
protected void RowCommand(object sender, GridViewCommandEventArgs e)
{
//if button is clicked
if (e.CommandName == "Clicked")
{
//go find the index on the gridview
int selectedIndex = MsgInbox.SelectedIndex;
if (int.TryParse(e.CommandArgument.ToString(), out selectedIndex))
{
//do something with database
}
Now that works beautifully. However, I don't want a button to be clickable, I want a entire row to be clickable. I know this is currently wrong, but this is what I have so far for the code:
.aspx code
<Columns>
<asp:TemplateField>
<ItemTemplate>
<asp:LinkButton ID="SelectRow" runat="server" ForeColor="red" CommandName="Clicked"></asp:LinkButton>
</ItemTemplate>
</asp:TemplateField>
C# code:
protected void Gridview_RowCreated(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
e.Row.Attributes["onmouseover"] = "this.style.cursor='pointer';this.style.textDecoration='underline';";
e.Row.Attributes["onmouseout"] = "this.style.textDecoration='none';";
var selectButton = e.Row.FindControl("SelectRow") as Button;
e.Row.Attributes["onclick"] = ClientScript.GetPostBackEventReference(selectButton, "");
I get a simple null pointer exception when I do this, but I'm not really familiar with e.Row.Attributes so I really have no idea where this is failing and what I need to do to add the database logic.
Thanks

It would be a lot simpler if you are ready to use jquery. For example,
<asp:GridView rowStyle-CssClass="row" ...
...
<asp:TemplateField>
<ItemTemplate>
<asp:LinkButton ID="SelectRow" runat="server" CommandName="Clicked" CssClass="selButton" />
</ItemTemplate>
</asp:TemplateField>
Note that each data row will have css class row and select button will have selButton
CSS would be some-thing like
tr.row { } /* normal row styling */
tr.row-highlight { background-color: blue; } /* highlighted row styling */
tr.row .selButton { display:none; visibility:hidden; } /* select button styling, I am using hidden button */
Finally the java-script
$(document).ready(function() {
$('tr.row').click(
function() {
// simulate click of select button
$(this).find('.selButton').click();
}).hover(
// add/remove css class to highlight on mouse over/out
function() { $(this).addClass('row-highlight'); },
function() { $(this).removeClass('row-highlight'); });
});

So I figured it out, and I'm sure there are better ways to implement it via jquery or javascript but I am not too good at either yet.
For my .aspx file, for the gridview, I simply added:
AutoGenerateSelectButton ="true"
In my C#, under MsgInbox_SelectedIndexChanged, I put all my RowCommand logic.
Finally, in C#, under my Gridview_RowCreated, I added this line to hide the Select link:
e.Row.Cells[0].Style["display"] = "none";

Related

To have OnSelect event without having Select button in GridView in ASP.net 4.0?

I am developing Web application in asp.net 4.0.
I am using a datagrid to display data from database.
I dont want to enable the select button feature of gridview in .net 4.0
But I want to have onRowSelected kind of event to populate on click of a row in gridview.
Please help me to achieve this!
Add templatefield with custom select button, hide it with css and attach that button click on row click event in GridView's RowDataBound event handler:
.hidden
{
display: none;
}
<asp:TemplateField HeaderStyle-CssClass="hidden" ItemStyle-CssClass="hidden" >
<ItemTemplate>
<asp:Button runat="server" ID="SelectButton" CommandName="Select" />
</ItemTemplate>
</asp:TemplateField>
void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
var selectButton = e.Row.FindControl("SelectButton") as Button;
e.Row.Attributes["onclick"] = ClientScript.GetPostBackEventReference(selectButton, "");
}
}

Set ASP.Net GridView column to Button field programmatically

I'm generating the columns of a gridview in code which is working fine (I have AutoGenerateColumns="false" set on the page), so I don't have any columns defined in the html markup.
I would like to make one of the columns a ButtonField, so I can use a RowCommand handler in the code - is there a way to make a column a ButtonField programmatically?
ButtonField programmatic adding:
var buttonField = new ButtonField
{
ButtonType = ButtonType.Button,
Text = "My button",
CommandName = "DoSomething",
};
Grid.Columns.Add(buttonField);
Markup:
<asp:GridView runat="server" ID="Grid" AutoGenerateColumns="false" OnRowCommand="RowCommandHandler"></asp:GridView>
Handler:
protected void RowCommandHandler(object sender, GridViewCommandEventArgs e)
{
if (e.CommandName == "DoSomething")
{
// place code here
}
}

LinkButton - bind field to ToolTip or CSSClass

I have a legacy asp.net 3.5 application. I need to bind a filed to CssClass so that i can utilize it via jquery.
Basically, in the datagrid, there are 2 buttons. Button one is visible and button two is not visible. On click of button one, i want to perform action and then make button two visible and hide button one. How can i do this? I just need a kick in the right direction...
<asp:LinkButton ID="lnkDelete" runat="server"
ToolTip="Delete Order <%# DataBinder.Eval(Container.DataItem, "TransID")%>"
OnClientClick="return DeleteOrder();"
OnClick="OrderDelete" CommandArgument='<%# Eval("TransID")'
CssClass="">
<asp:Image ID="Image1" runat="server" ImageUrl="~/images/icons/delete.gif"
BorderStyle="None" />
</asp:LinkButton>
My current binding inside the tooltip results in an error, "the server tag is not well formed".
On the code behind OrderDelete, i can disable the delete link, but how can i make the other button visible?
//delete indivisual order
protected void OrderDelete(object sender, EventArgs e)
{
string transactionID = String.Empty;
LinkButton lnkDelete = (LinkButton)sender;
if (lnkDelete != null)
transactionID = lnkDelete.CommandArgument;
if (!String.IsNullOrEmpty(transactionID))
{
//do delete
}
//refresh results
}
For the server tag not well-formed error, try something like this:
ToolTip='<%# String.Format("Delete Order {0}", DataBinder.Eval(Container.DataItem, "TransID")%>'
For the second part of your question, a little more of your code might help to give you a more specific answer, but in lieu of that, if you know which row of the DataGrid you're in, you should be able to do a FindControl in that row for the second button and make it visible.
Update
You might try setting the tooltip in the codebehind, using the RowDataBound event. Something like this:
protected void gv1_RowDataBound(object sender, GridViewRowEventArgs e)
{
if(e.Row.RowType == DataControlRowType.DataRow)
{
LinkButton btn = e.Row.FindContorl("lnkDelete") as LinkButton;
// You'll need to retrieve the values you want to dynamically populate
// the ToolTip with from other controls in the row;
// I don't know if you'd be able to use the DataSource or not, but you might.
btn.ToolTip = "Delete Order ";
}
}

How to add a "confirm delete" option in ASP.Net Gridview?

How to add a "confirm delete" option in ASP.Net Gridview ?
This should do it.
I found it here: http://forums.asp.net/p/1331581/2678206.aspx
<asp:TemplateField ShowHeader="False">
<ItemTemplate>
<asp:ImageButton ID="DeleteButton" runat="server" ImageUrl="~/site/img/icons/cross.png"
CommandName="Delete" OnClientClick="return confirm('Are you sure you want to delete this event?');"
AlternateText="Delete" />
</ItemTemplate>
</asp:TemplateField>
If your Gridview used with AutoGenerateDeleteButton="true" , you may convert it to LinkButton:
Click GridView Tasks and then Edit Columns.
Select Delete in Selected fields, and click on Convert this field into a TemplateField. Then click OK:
Now your LinkButton will be generated. You can add OnClientClick event to the LinkButton like this:
OnClientClick="return confirm('Are you sure you want to delete?'); "
I did this a bit different. In my gridview I set the AutoGenerateDeleteButton="true". To find the delete button I use jQuery and add a click event to the found Anchors.
jQuery("a").filter(function () {
return this.innerHTML.indexOf("Delete") == 0;
}).click(function () { return confirm("Are you sure you want to delete this record?");
});
This is quick and simple for what I need to do. Just be mindful that Every Anchor in the page that displays Delete will be selected by jQuery and will have the event added to it.
I like this way of adding a confirmation prompt before deleting a record from a gridview. This is the CommandField definition nested within a GridView web control in the aspx page. There's nothing fancy here--just a straightforward Commandfield.
<asp:CommandField ShowEditButton="true" UpdateText="Save" ShowDeleteButton="True">
<ControlStyle CssClass="modMarketAdjust" />
</asp:CommandField>
Then, all I had to do was add some code to the RowDeleting event of the GridView control. This event fires before the row is actually deleted, which allows you to get the user's confirmation, and to cancel the event if he doesn't want to cancel after all. Here is the code that I put in the RowDeleting event handler:
Private Sub grdMarketAdjustment_RowDeleting(sender As Object, e As GridViewDeleteEventArgs) Handles grdMarketAdjustment.RowDeleting
Dim confirmed As Integer = MsgBox("Are you sure that you want to delete this market adjustment?", MsgBoxStyle.YesNo + MsgBoxStyle.MsgBoxSetForeground, "Confirm Delete")
If Not confirmed = MsgBoxResult.Yes Then
e.Cancel = True 'Cancel the delete.
End If
End Sub
And that seems to work fine.
I didn't want any image so i modified the answer given by #statmaster to make it simple entry along with the other columns.
<asp:TemplateField ShowHeader="False">
<ItemTemplate>
<asp:LinkButton ID="LinkButton1" runat="server" CommandName="Delete" OnClientClick="return confirm('Are you sure you want to delete this entry?');">Delete </asp:LinkButton>
</ItemTemplate>
</asp:TemplateField>
The colour of the text can be changed using the Forecolor Property.
You can do using OnClientClick of button.
OnClientClick="return confirm('confirm delete')"
I quite like adding the code in the GridView RowDataBound event to inform the user exactly which item they are trying to delete. Slightly better user experience?
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
LinkButton lnkBtnDelete = e.Row.FindControl("lnkBtnDelete") as LinkButton;
// Use whatever control you want to show in the confirmation message
Label lblContactName = e.Row.FindControl("lblContactName") as Label;
lnkBtnDelete.Attributes.Add("onclick", string.Format("return confirm('Are you sure you want to delete the contact {0}?');", lblContactName.Text));
}
}
Try this:
I used for Update and Delete buttons. It doesn't touch Edit button. You can use auto generated buttons.
protected void gvOperators_OnRowDataBound(object sender, GridViewRowEventArgs e)
{
if(e.Row.RowType != DataControlRowType.DataRow) return;
var updateButton = (LinkButton)e.Row.Cells[0].Controls[0];
if (updateButton.Text == "Update")
{
updateButton.OnClientClick = "return confirm('Do you really want to update?');";
}
var deleteButton = (LinkButton)e.Row.Cells[0].Controls[2];
if (deleteButton.Text == "Delete")
{
deleteButton.OnClientClick = "return confirm('Do you really want to delete?');";
}
}
This is my preferred method. Pretty straight forward:
http://www.codeproject.com/KB/webforms/GridViewConfirmDelete.aspx
Although many of these answers will work, this shows a straightforward example when using CommandField in GridView using the OnClientClick property.
ASPX:
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="false" OnRowDataBound="OnRowDataBound"... >
<Columns>
<!-- Data columns here -->
<asp:CommandField ButtonType="Button" ShowEditButton="true" ShowDeleteButton="true" ItemStyle-Width="150" />
</Columns>
</asp:GridView>
ASPX.CS:
protected void OnRowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow && e.Row.RowIndex != GridView1.EditIndex)
{
(e.Row.Cells[2].Controls[2] as Button).OnClientClick = "return confirm('Do you want to delete this row?');";
}
}
I was having problems getting a commandField Delete button to honor the 'return false' response to when a user clicked cancel on the 'Are you sure' pop-up that one gets with using the javascript confirm() function. I didn't want to change it to a template field.
The problem, as I see it, was that these commandField Buttons already have some Javascript associated with them to perform the postback. No amount of simply appending the confirm() function was effective.
Here's how I solved it:
Using JQuery, I first found each delete button on the page (there are several), then manipulated the button's associated Javascript based on whether the visitor agreed or canceled the confirming pop-up.
<script language="javascript" type="text/javascript">
$(document).ready(function() {
$('input[type="button"]').each(function() {
if ($(this).val() == "Delete") {
var curEvent = $(this).attr('onclick');
var newContent = "if(affirmDelete() == true){" + curEvent + "};"
$(this).attr('onclick',newContent);
}
});
}
function affirmDelete() {
return confirm('Are you sure?');
}
</script>
This code is working fine for me.
jQuery("a").filter(function () {
return this.innerHTML.indexOf("Delete") == 0;
}).click(function () { return confirm("Are you sure you want to delete this record?");
});
I love the JavaScript solution and have some updates to work with dynamic ajax loading:
$(document).on("click", "a", function () {
if (this.innerHTML.indexOf("Delete") == 0) {
return confirm("Are you sure you want to delete this record?");
}
});
Hope it help ;)
This is my method and it works perfectly.
asp
<asp:CommandField ButtonType="Link" ShowEditButton="true" ShowDeleteButton="true" ItemStyle-Width="5%" HeaderStyle-Width="5%" HeaderStyle-CssClass="color" HeaderText="Edit"
EditText="<span style='font-size: 20px; color: #27ae60;'><span class='glyphicons glyph-edit'></span></span>"
DeleteText="<span style='font-size: 20px; color: #c0392b;'><span class='glyphicons glyph-bin'></span></span>"
CancelText="<span style='font-size: 20px; color: #c0392b;'><span class='glyphicons glyph-remove-2'></span></span>"
UpdateText="<span style='font-size: 20px; color: #2980b9;'><span class='glyphicons glyph-floppy-saved'></span></span>" />
C# (replace 5 with the column number of the button)
if ((e.Row.RowState & DataControlRowState.Edit) > 0)
{
}
else {
((LinkButton)e.Row.Cells[5].Controls[2]).OnClientClick = "return confirm('Do you really want to delete?');";
}

Why won't my LinkButton inside a GridView raise its OnClick event?

I have a LinkButton inside a GridView (via an TemplateField). No matter what I try, the LinkButton will not invoke its event handler. I have tried both:
A traditional event handler ("OnClick")
A OnRowCommand event handler at the GridView level.
In both cases, I've debugged and it doesn't even catch the event handler.
If I move the LinkButton out on the page (so it's not in the GridView), it works fine, so I know the syntax is right.
Here is the "traditional" method:
<asp:TemplateField>
<ItemTemplate>
<asp:LinkButton Text="Cancel" ID="DeleteButton" CausesValidation="false" OnClick="CancelThis" runat="server" />
</ItemTemplate>
<asp:TemplateField>
What's interesting is if I remove the "CancelThis" method from the code behind, it throws an error. So I know it's aware of its event handler, because it looks for it when it compiles.
Here is the RowCommand method:
<asp:TemplateField>
<ItemTemplate>
<asp:LinkButton Text="Cancel" ID="DeleteButton" CausesValidation="false" CommandName="CancelThis" runat="server" />
</ItemTemplate>
<asp:TemplateField>
In this case, the GridView has:
OnRowCommand="GridView_RowCommand"
It postsback, but never hints at raising the event.
Any idea what I'm missing here?
How are you binding your GridView? Are you using a datasource control? If you are binding manually during Page_Load, it's possible that since the grid is binding every round trip, the event handler isn't catching properly. If this is the case, you may want to try something like:
protected void Page_Load(object sender, EventArgs e)
{
if(!Page.IsPostBack)
{
//do binding
}
}
Can you post sample binding code to go with your markup?
If you really want to force the issue, you could hook into the RowDataBound event on the Grid, find the button manually and add the handler in the code behind. Something like:
markup snippet:
<asp:GridView ID="gvTest" runat="server" OnRowDataBound="gvTest_RowDataBound" />
code behind:
protected void gvTest_RowDataBound(object sender, GridViewRowEventArgs e)
{
if(e.Row.RowType == DataControlRowType.DataRow)
{
//find button in this row
LinkButton button = e.Row.FindControl("DeleteButton") as button;
if(button != null)
{
button.Click += new EventHandler("DeleteButton_Click");
}
}
}
protected void DeleteButton_Click(object sender, EventArgs e)
{
LinkButton button = (LinkButton)sender;
// do as needed based on button.
}
I'm not sure what the purpose of the button is, but assuming it is a row delete button, you may not want to take this approach as in the event handler, you don't have direct access to the row in question, like you would using the RowCommand event.
Is there a reason you're using the Template field? Vs say a ButtonField? If you use a ButtonField, then you can hook into the RowCommand event.
markup snippet:
<asp:GridView ID="gvTest" runat="server" OnRowCommand="gvTest_RowCommand">
<columns>
<asp:buttonfield buttontype="Link" commandname="Delete" text="Delete"/>
....
</columns>
</asp:GridView>
code behind:
protected void gvTest_RowCommand(object sender, GridViewCommandEventArgs e)
{
if(e.CommandName == "Delete")
{
//take action as needed on this row, for example
int rowIndex = Convert.ToInt32(e.CommandArgument);
GridViewRow currentRow = (sender as GridView).Rows[rowIndex];
//do something against the row...
}
}
You might want to consult MSDN docs on some of these topics:
RowCommandEvent
ButtonField class
EDIT:
To answer your question on the ButtonField - yes I don't see why you couldn't still deal with a buttonfield. Here's a snippet to find the buttonfield during row data bound and hide it (untested but I think would work...)
protected void gvTest_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
//let's assume your buttonfield is in column 1
// (you'd know this based on your markup...)
DataControlFieldCell cell = e.Row.Cells[1] as DataControlFieldCell;
if(cell != null)
{
ButtonField field = cell.ContainingField as ButtonField;
//based on your criteria, show or hide the button
field.Visible = false;
//or
field.Visible = true;
}
}
}
Is viewstate turned on on your GridView? This has caught me out numerous times.
<button onclick="window.open('<%#Eval("ReportLinks")%>', '_blank');" title='<%#Eval("ReportLinks")%>'> Link</button>

Resources