Binding a Button to a GridView - c#

This a pretty simple question, I'm just not sure how to do it exactly. I would like to bind a Button or perhaps ImageButton to a GridView in ASP.NET/C#. Currently, the GridView has two columns and is bound to a DataTable with two columns. I want to add a third column to the GridView, which will include the Button.
I know GridView has ButtonField, but I'm not too sure how to go about using it to do what I want. I want to dynamically generate these Buttons and add them to the GridView.
Here is how my GridView looks right now:
<asp:GridView
ID="GridView1"
Runat="server">
<Columns>
<asp:HyperLinkField
HeaderText="Display Name"
DataNavigateUrlFields="DISPNAME"
DataNavigateUrlFormatString="ViewItem.aspx"
DataTextField="DISPNAME">
<ItemStyle Width="70%" />
</asp:HyperLinkField>
<asp:BoundField
DataField="TypeDisp"
HeaderText="Type">
<ItemStyle Width="20%" />
</asp:BoundField>
</Columns>
</asp:GridView>

You can use a template field like the following,
<TemplateField>
<ItemTemplate>
<asp:ImageButton ImageUrl="image url" CommandName="SomeCommand" CommandArgument='<%# Eval("Id") %>'/>
</ItemTemplate>
</TemplateField>
Then you can handle the RowCommand event of the GridView and check the e.CommandName to see what command to be executed and you can get the e.CommandArgument as well which could be the row Id like I used in the code above.

If we are talking a button that's always present, you can use ButtonField, or even use a TemplateField and provide the template with the button, and bind the data to the button (sounds like you may want to bind data to the attributes of the button?)
If you are looking to dynamically generate buttons in the UI, tap into the RowCreated event and add the button the GridView. You'd have to do this on every page load; the GridView won't remember a button created programmatically.
HTH.

Related

Cannot activate RowDataBound event for ASP.NET Gridview

I am working through an ASP.NET C# tutorial. I have a simple Gridview with the auto-created Edit & Delete Commandfields. So I've converted the Delete command field to a Templatefield and now I am trying to access the RowDataBound event of the Datagrid to add some code.
When I view the Gridview properties and click on the Events, I can see the RowDataBound event, but when I double-click on that event nothing happens. How do I create my event code? (in fact, I can't double-click on any of the events - they are all disabled).
Here is the top section of code for my gridview:
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" CellPadding="4" DataKeyNames="colorID"
DataSourceID="SqlDataSource1" ForeColor="#333333" GridLines="None" ShowFooter="True">
<AlternatingRowStyle BackColor="White" />
<Columns>
<%-- Edit Button --%>
<asp:CommandField ShowEditButton="True" />
<%-- Delete Button --%>
<asp:TemplateField ShowHeader="False">
<ItemTemplate>
<asp:LinkButton ID="LinkButton1" runat="server" CausesValidation="False"
CommandName="Delete" Text="Delete"></asp:LinkButton>
</ItemTemplate>
</asp:TemplateField>
Thanks for your help.
John
When I create a gridview, the turn-on of edits, deletes, and inserts as commandfields works fine. Also if I immediately convert the delete commandfield to a templatefield before I do anything else, then the RowDataBound event (and all of the other events) are active and I can build codebehind content.
So, for now, something in the tutorial I am using is changing the character of the gridview events. Mostly, I was trying to dialog "Are you sure you want to delete Item XYZ?" as a validating Eval of the row I am deleting. But for now, with too many other things to learn, I'll just live with the stock OnClientClick="return confirm('Are you sure?'); and move on to something else that's more important.

Recording clicked Grid View column

I have a grid view in a asp page which have a hyperlink field,say,CustomerID which navigates user to various webpages. The value of the CustomerID in the grid view can have duplicate values. So, what I want is how to record all the clicked values in the CustomerID or the hyperlink?
Please suggest solution such that the solution is viable for multiple hyperlink column in gridview each navigation to different webpage.
You can use combination of gridview bind columns and pass them as parameters in url and retrieve in other page as Request.QueryString[] collection.
Eg
<asp:TemplateField>
<ItemTemplate>
<asp:HyperLink runat="server" NavigateUrl='<%# string.Format("~/Details.aspx?CustomerID={0}&Name={1}&Country={2}",
HttpUtility.UrlEncode(Eval("CustomerID").ToString()), HttpUtility.UrlEncode(Eval("Name").ToString()), HttpUtility.UrlEncode(Eval("Country").ToString())) %>'
Text="View Details" />
</ItemTemplate>
</asp:TemplateField>

.NET framework 4.5 loads default edit template on GridView?

I've created a gridview with edit feature. On clicking the gridview row edit image, it makes the custom edit panel visible and the user can edit and save the gridview row data or s/he can click the cancel button without any updates. It works perfectly fine with .NET framwork 2.0.
But, the problem lies with the .NET framework 4.5 -
when the user clicks the cancel or save button, instead of loading the
normal gridview, it loads the default edit template on the top of
gridview row where the user had clicked before.
So, how can I solve this problem? This happens in all the Gridviews used in our ASP.NET website.
Here's the original Gridview Row: Original GridRow
Here's the custom edit panel with save/cancel: Custom Edit Panel
Here's error: Default Template loaded
I usually achieve what you are trying to do in the row databound event.
Try setting up your grid view like this
<asp:Gridview id="ClientManagementGridView runat="server"/>
<columns>
<asp:TemplateField>
<itemtemplate>
//put edit button here
</itemtemplate>
<edititemtemplate>
// put your update and cancel buttons here
</edititemtemplate>
</asp:Templatefield>
<asp:templatefield>
<itemtemplate>
<aspTextBox Text='<#Eval("ClientId") %>' runat="server" />
</itemtemplate>
<edititemtemplate>
<asp:Panel id="EditPanel">
//your panel contents
</asp:Panel>
</edititemtemplate>
</asp:templateField>
<asp:BoundField DataField="ClientName" HeaderText="Name" />
<asp:BoundField DataField="Address" HeaderText="Name" />
</columns>
<asp:GridView>
Now in your row data bound event of your gridview put this magic piece of code
If e.Row.RowState.ToString().Contains("Edit") Then
Dim editGrid As GridView = TryCast(sender, GridView)
Dim colSpan As Integer = editGrid.Columns.Count
e.Row.Cells(0).Visible = True
e.Row.Cells(1).Visible = True
For i As Integer = 2 To colSpan - 1
e.Row.Cells(i).Visible = False
e.Row.Cells(i).Controls.Clear()
Next
e.Row.Cells(1).Attributes("ColSpan") = (colSpan).ToString()
End if
As you can see I am overriding the default edit item template by clearing its default controls and then changing the column span of the cell to fit my custom edit panel.As well as hiding cells I want to be hidden.

how to add a link button in the grid view by visual studio?

I want to add a link button in grid view that will navigate to the next form in the website. but i want to know how to insert that button into the grid view column? please help me..
You can add Link buttons in the Item template of a gridview.
<asp:TemplateField>
<ItemTemplate>
<asp:LinkButton ID="Link" runat="server" PostBackUrl="MyNextPage.aspx">Edit</asp:LinkButton>
</ItemTemplate>
</asp:TemplateField>
<Columns>
<asp:TemplateField>
<HeaderTemplate>
// TEXT FOR COLUMN NAME
</HeaderTemplate>
<ItemTemplate>
// ADD LINK BUTTON HERE.
</ItemTemplate>
</asp:TemplateField>
</Columns>
Add this inside grid view.
try this
<asp:GridView ID="GridView1" runat="server">
<Columns>
<asp:ButtonField ButtonType="Link" HeaderText="LinkButton"/>
</Columns>
</asp:GridView>
Make Sure your GridViews datasource is bound. Set Auto-Generate Columns to false.
Open GridViewTask , add new column with Hyperlink Field proper name and path . You are done.

Retain form data while paging through a GridView - ASP.NET

I have a GridView control on my ASP.NET page that binds to result set when the user executes a search. I create an additional TemplateField column with a CheckBox control to allow the user to select a sub set of records from the result set. I have implemented paging in the GridView control and when the user checks the checkbox control and pages through the result set it does not retain any of the checked checkboxes.
<asp:GridView ID="MyGridView" runat="server" AllowPaging="true" AutoGenerateColumns="false">
<Columns>
<asp:TemplateField>
<ItemTemplate>
<asp:CheckBox ID="MyCheckBox" runat="server" />
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
Whaat is the best way to retain the checked checkboxes while paging through the GridView?
You have to maintain the state yourself. This Thread shows how this can be done in VB. just use this VB to C# converter to get your desired code
you'll need to loop over the rows and save the checked state of the check boxes (along with a datakey) during the gridview paging event. Likewise you will need to read from your saved check state list to re-check the boxes during the gridview rowdatabound event.

Categories