C# How do I create a Hyperlink OnClick event on GridView? - asp.net

I'm having trouble creating the GridView I want.
I would like the user to get inside the website and see the GridView which is attached to a DB.
Columns are: ID, InsertionTime, Filepath, ProccessedByUser
Now I want the user to click the filepath he/she would like to process. When he/she clicks the filepath, I want their username (logged in with built-in asp website authentication) to be updated (added) into DB.
My markup is standard and I haven't got to manage with code behind.
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False"
DataKeyNames="ID" DataSourceID="AccessDataSource1"
onselectedindexchanged="GridView1_SelectedIndexChanged">
<Columns>
<asp:BoundField DataField="ID" HeaderText="ID" InsertVisible="False"
ReadOnly="True" SortExpression="ID" />
<asp:BoundField DataField="starttime" HeaderText="starttime"
SortExpression="starttime" />
<asp:HyperLinkField DataNavigateUrlFields="path" DataTextField="path"
HeaderText="path" />
<asp:BoundField DataField="user" HeaderText="user" SortExpression="user" />
</Columns>
</asp:GridView>
I tried using HyperlinkField but it doesn't seem to support onlick events.
Any suggestions?
Thanks.

I assume you are looking for the LinkButton control which has an OnClick event.
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False"
DataKeyNames="ID" DataSourceID="AccessDataSource1"
onselectedindexchanged="GridView1_SelectedIndexChanged">
<Columns>
<asp:BoundField DataField="ID" HeaderText="ID" InsertVisible="False"
ReadOnly="True" SortExpression="ID" />
<asp:BoundField DataField="starttime" HeaderText="starttime"
SortExpression="starttime" />
<asp:TemplateField HeaderText="Path" SortExpression="Filepath">
<ItemTemplate>
<asp:LinkButton ID="LbPath" runat="server"
Text='<%# Eval("Filepath") %>'
CommandName="PathUpdate"
CommandArgument='<%#Bind("path") %>'>
</asp:LinkButton>
</ItemTemplate>
</asp:TemplateField>
<asp:BoundField DataField="user" HeaderText="user" SortExpression="user" />
</Columns>
</asp:GridView>
Now you can handle the LinkButton's click event or the GridView's RowCommand event.
protected void Gridview1_RowCommand(object sender, GridViewCommandEventArgs e)
{
if (e.CommandName == "PathUpdate")
{
string path= e.CommandArgument.ToString();
// do you what you need to do
}
}
Note that i've used a TemplateField which is the most dynamic column type in a GridView since you can add anything you want, even nested GridViews or UserControls.

You could use a ButtonField, and then handle OnRowCommand of the gridview. Example here:
http://msdn.microsoft.com/SV-SE/library/system.web.ui.webcontrols.buttonfieldbase.buttontype.aspx
You can set the ButtonType attribute of ButtonField to display the button as a Link.

Related

ASP.net make Buttons set GridView Visible property to True or False

I have an ASP.net web page that has 2 gridviews. I have 2 buttons where I want to be able to click one to make 1 gridview visible and the other hidden, and the other button to make the first gridview hidden and the 2nd gridview visible. When I click either of them nothing happens. I've played around with the gridview visible settings w/ no luck.I'm sure its simple. Thanks for looking! Some code is below:
The 2 Gridviews:
<asp:GridView ID="gridShowUsers" runat="server" AutoGenerateColumns="False" DataKeyNames="user_id" DataSourceID="SqlDataSource1" AllowPaging="True">
<Columns>
<asp:CommandField ShowDeleteButton="True" ShowEditButton="True" />
<asp:BoundField DataField="user_id" HeaderText="User ID" InsertVisible="False" ReadOnly="True" SortExpression="user_id" />
<asp:BoundField DataField="user_name" HeaderText="Username" SortExpression="user_name" />
<asp:BoundField DataField="user_password" HeaderText="Password" SortExpression="user_password" />
<asp:BoundField DataField="user_securitylevel" HeaderText="Security Level" SortExpression="user_securitylevel" />
</Columns>
</asp:GridView>
<asp:GridView ID="gridOrders" runat="server" AllowSorting="True" AutoGenerateColumns="False" DataKeyNames="ordr_id" DataSourceID="SqlDataSource2" EmptyDataText="There are no Orders to Display" AllowPaging="True">
<Columns>
<asp:CommandField ShowDeleteButton="True" ShowEditButton="True" ShowSelectButton="True" />
<asp:BoundField DataField="ordr_id" HeaderText="ordr_id" InsertVisible="False" ReadOnly="True" SortExpression="ordr_id" />
<asp:BoundField DataField="ordr_date" HeaderText="ordr_date" SortExpression="ordr_date" />
<asp:BoundField DataField="ordr_fname" HeaderText="ordr_fname" SortExpression="ordr_fname" />
<asp:BoundField DataField="ordr_lname" HeaderText="ordr_lname" SortExpression="ordr_lname" />
<asp:BoundField DataField="ordr_streetaddress" HeaderText="ordr_streetaddress" SortExpression="ordr_streetaddress" />
<asp:BoundField DataField="ordr_city" HeaderText="ordr_city" SortExpression="ordr_city" />
<asp:BoundField DataField="ordr_state" HeaderText="ordr_state" SortExpression="ordr_state" />
<asp:BoundField DataField="ordr_zipcode" HeaderText="ordr_zipcode" SortExpression="ordr_zipcode" />
</Columns>
</asp:GridView>
Code behind for the buttons:
protected void btnShowUsers_Click(object sender, EventArgs e)
{
gridShowUsers.Visible = true;
gridOrders.Visible = false;
}
protected void btnShowOrders_Click(object sender, EventArgs e)
{
gridShowUsers.Visible = false;
gridOrders.Visible = true;
}
Basically your code SHOULD work, but maybe something is wrong with the overall context. Please also provide the code of your buttons, and maybe the full page code - or is this stuff maybe in UpdatePanels?
Anyway, does it have to happen via a postback, meaning in the c#-code? Otherwise I would propose you use client side solutions, f.e. jQuery or javascript.
In jQuery you could do it like this (assuming your button IDs):
$("#btnShowUsers").on("click", function(){
$("#gridShowUsers").show();
$("#gridOrders").hide();
});
$("#btnShowOrders").on("click", function(){
$("#gridShowUsers").hide();
$("#gridOrders").show();
});
This also enables you to do fancy stuff like animations (try .hide(500)) or use functions like toggle(), and it doesn't cause a postback and therefore doesn't reload the whole page.
Don't forget to add the lates stable jQuery library to your asp.net -section (https://developers.google.com/speed/libraries/#jquery):
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.4/jquery.min.js"></script>

Adding a new column with buttons in gridview and binding data to it

I have added a button for Print in my gridview table as follows
<asp:GridView ID="GridView1" runat="server" AllowPaging="True"
AllowSorting="True" AutoGenerateColumns="False" DataKeyNames="ID"
DataSourceID="SqlDataSource2"
onselectedindexchanged="GridView1_SelectedIndexChanged" Width="522px">
<Columns>
<asp:BoundField DataField="ID" HeaderText="ID" InsertVisible="False"
ReadOnly="True" SortExpression="ID" />
<asp:BoundField DataField="Story_number" HeaderText="Story_number"
SortExpression="Story_number" />
<asp:BoundField DataField="Date" HeaderText="Date" SortExpression="Date" />
<asp:BoundField DataField="Memory_card" HeaderText="Memory_card"
SortExpression="Memory_card" />
<asp:BoundField DataField="Story_Name" HeaderText="Story_Name"
SortExpression="Story_Name" />
<asp:ButtonField ButtonType="Button" Text="print" />
</Columns>
</asp:GridView>
Please help me with the c# code for this button. When the button is pressed I need it to redirect to a page (print.aspx). I have been trying the following code but it does not work .Thanks in advance for your help.
Session["id"] = GridView1.SelectedRow.Cells[0].Text;
Response.Redirect("Print.aspx");
Instead of buttonField, use template field
<asp:TemplateField>
<ItemTemplate>
<asp:ImageButton ID="ButtonPrint" runat="server" CssClass="yourCssClassIsNeedIt" OnClick="printRegFunction"
CommandArgument='<%# Bind("id") %>' ImageUrl="images/button.png"/>
</ItemTemplate>
</asp:TemplateField>
your server code or behind code here:
protected void printRegFunction(object sender, ImageClickEventArgs e)
{
Session["id"] = ((ImageButton)sender).CommandArgument;
Response.Redirect("Print.aspx");
}

Using asp:Button with OnRowDeleting event

I'm trying to connect an asp:Button with my OnRowDeleting event in a gridview, but I don't don't know how to do that :X. I'm currently using CommandField but for my own purposes I need it with a Button instead. Can anyone help me please?
EDIT:
Let me re-explain, I have a row with Delete and Edit buttons in the same CommandField. What I'm trying to do is to hide the 'Delete' button in some specific cases for specific rows only and not necessarily for every row. That's why I'm struggling with a CommandField because there's no ID coming with it so I can't refer to it in my codebehind. But - asp:Button has an ID but I can't manage to link it with the UserAccounts_RowDeleting function. And that's my question - how to link it? :)
EDIT2:
These are part of my codes:
<asp:GridView ID="UserAccounts" runat="server" AutoGenerateColumns="False" HeaderStyle-BackColor="#3AC0F2"
HeaderStyle-ForeColor="White" AutoGenerateDeleteButton="false"
RowStyle-BackColor="#A1DCF2" AlternatingRowStyle-BackColor="White" AutoGenerateEditButton="false"
onrowcancelingedit="UserAccounts_RowCancelingEdit" RowStyle-ForeColor="#3A3A3A" OnRowEditing="UserAccounts_RowEditing"
PageSize="10" AllowPaging="false" onrowdeleting="UserAccounts_RowDeleting"
OnRowUpdating="UserAccounts_RowUpdating" OnRowDataBound="UserAccounts_RowDataBound" onrowcreated="UserAccounts_RowCreated">
<Columns>
<asp:CommandField ShowDeleteButton="true" ShowEditButton='true' ButtonType="Link" />
<asp:BoundField DataField="UserName" HeaderText="Username" ReadOnly="true"/>
<asp:BoundField DataField="Email" HeaderText="Email" />
<asp:CheckBoxField DataField="IsApproved" HeaderText="Approved?" ReadOnly="false"/>
<asp:CheckBoxField DataField="IsLockedOut" HeaderText="Locked Out?" ReadOnly="true"/>
<asp:CheckBoxField DataField="IsOnline" HeaderText="Online?" ReadOnly="true"/>
<asp:BoundField DataField="Comment" HeaderText="Comment" NullDisplayText="N/A"/>
<asp:TemplateField HeaderText="Select" >
<ItemTemplate>
<asp:CheckBox ID="CheckBox1" runat="server" />
</ItemTemplate>
</asp:TemplateField>
</Columns>
//Codebehind c#
protected void UserAccounts_RowDeleting(object sender, GridViewDeleteEventArgs e)
{
if (Funcs.GetAdminLevel() >= 999)
{
username = UserAccounts.Rows[e.RowIndex].Cells[1].Text;
if (username.ToLower().Equals(HttpContext.Current.User.Identity.Name.ToLower()))
ActionStatus.Text = string.Format("ERROR: You can't delete your own account ('<font color=#000000><b>{0}</b></font>')!", username);
else if (Funcs.GetAdminLevel(username) >= 1)
ActionStatus.Text = string.Format("ERROR: You can't delete administrators' accounts ('<font color=#000000><b>{0}</b></font>')!", username);
else
{
Roles.RemoveUserFromRoles(username, Roles.GetRolesForUser(username));
Membership.DeleteUser(username);
ActionStatus.Text = string.Format("User '<font color=#000000><b>{0}</b></font>' has been successfully deleted!", username);
BindUserAccounts();
}
}
else
ActionStatus.Text = "You are not authorized to delete user accounts!";
}
I want to change the CommandField to ItemTemplate so I can enable/disable it through the codebehind for specific rows only. Also, I want the ItemTemplate, which would be asp:Button, to use the UserAccounts_RowDeleting event and that's where my problem is, I just don't know how to link the button to the event..
It sounds like you pretty much have the solution already. Use a TemplateField for your button. The key part is to set the CommandName of your button to "Delete". This tells the GridView that it is a delete button and the RowDeleting event should handle it.
<asp:TemplateField>
<ItemTemplate>
<asp:Button ID="btnDelete" runat="server" Text="Delete" CommandName="Delete" />
</ItemTemplate>
</asp:TemplateField>

How to get the Textbox value from DataGridView?

So here I'm trying to get the Textbox filled with the selected data from the DataGridView, so when I clicked the button in the DataGridView, the selected result will be put into the Textbox, I've tried the solution from other resource but still no luck. Can somebody help? Here's the DataGridView code:
DataGridView:
<asp:Panel ID="PanelDGV" runat="server" ScrollBars="None" Height="250" Width="515">
<asp:GridView ID="DGV" runat="server" AutoGenerateColumns="False" GridLines="None" AllowPaging="true" PageSize="8" CssClass="mGrid" PagerStyle-CssClass="pgr" AlternatingRowStyle-CssClass="alt">
<Columns>
<asp:BoundField DataField="ProjectCode" HeaderText="Project Code" />
<asp:BoundField DataField="ProjectName" HeaderText="Project Name" />
<asp:ButtonField ButtonType="Image" ImageUrl="../Support/Image/Edit.png" ItemStyle-HorizontalAlign="Center" CommandName="CmdSearch" HeaderText="Edit">
<ItemStyle HorizontalAlign="Center"></ItemStyle>
</asp:ButtonField>
</Columns>
<PagerStyle CssClass="pgr"></PagerStyle>
AlternatingRowStyle CssClass="alt"></AlternatingRowStyle>
</asp:GridView>
</asp:Panel>
notice the button is:
<asp:ButtonField ButtonType="Image" ImageUrl="../Support/Image/Edit.png" ItemStyle-HorizontalAlign="Center" CommandName="CmdSearch" HeaderText="Edit">
oh, and the textbox's ID is "TbProjectCode", and both are in separate pages, say that 1.aspx contain the textbox and a button to open the datagridview and 2.aspx contain the datagridview and the button to select the Project Code.
thank you
Add OnRowCommand event on your gridview: OnRowCommand="DGV_OnRowCommand".
Then add this on your code behind:
protected void DGV_OnRowCommand(object sender, GridViewCommandEventArgs e)
{
if (e.CommandName == "CmdSearch")
{
int index = (int)e.CommandArgument;
GridViewRow row = DGV.Rows[index];
// Get the text on first cell of the row which is the project code.
TbProjectCode.Text = row.Cells[0].Text;
}
}

GridView ASP.NET Sorting

I have an ASP.NET GridView that just won't sort! I'm sure that I am missing something pretty obvious.
Page.aspx
<asp:GridView ID="TimeAwayGridView" runat="server" AutoGenerateSelectButton="False"
AutoGenerateEditButton="False" AutoGenerateDeleteButton="False" AllowPaging="False"
AllowSorting="True" CssClass="gridview" OnSorting="TimeAwayGridView_Sorting">
<Columns>
<asp:BoundField DataField="Description" HeaderText="Description" SortExpression="Description" />
<asp:BoundField DataField="Hours" HeaderText="Hours" SortExpression="Hours" />
</Columns>
<EmptyDataTemplate>
There are currently no items in this table.
</EmptyDataTemplate>
</asp:GridView>
Page.aspx.cs
protected void TimeAwayGridView_Sorting(object sender, GridViewSortEventArgs e)
{
}
Asp.Net Datagrip provides you with sorting event, and name of the column that was clicked in GridViewSortEventArgs, but you have to provide you own sort implementation in TimeAwayGridView_Sorting function. Meaning you should sort your datasource and rebind the datagrid.

Resources