Is there someway to turn the row of a gridview into a hyperlink so that when a user opens it in a new tab for example, it goes to that link? Right now I am using a LinkButton and when the user opens it in a new tab, it doesn't know where to go.
I figured the .aspx code would look something like:
<asp:TemplateField>
<ItemTemplate>
<Hyperlink ID="hyperlink" runat="server" ForeColor="red" HtmlEncode="false" navigationURL="testUrl.aspx"
</ItemTemplate>
</asp:TemplateField>
The only thing is, our URLs are set up in the C# code behind as a query string, so I'm not sure how to pass that into the navigationURL section.
I'm guessing there's something I can do on the page_load with the query string to redirect to the page I need, but this is my first time working with query strings so I'm a little confused.
Thanks!
<asp:TemplateField>
<ItemTemplate>
<asp:HyperLink ID="HyperLink1" runat="server" NavigateUrl='<%#String.Format("~/controller.aspx?routeID1={0}&routeID2={1}", Eval("routeid1"), Eval("routeid2"))%>'></asp:HyperLink>
</ItemTemplate>
</asp:TemplateField>
routeid1 and routeid2 are passed as query strings to the controller of that page.
What I did recently is modified my class to have a readonly property that constructs the A tag for me. This way I have control over what gets displayed; just text or a link.
<ItemTemplate>
<asp:Label ID="ColumnItem_Title" runat="server" Text='<%# Bind("DownloadATag") %>'> </asp:Label>
</ItemTemplate>
The code behind just binds an instance of the class to the gridview. You can bind the gridview whenever, on load on postback event, etc.
Dim docs As DocViewList = GetViewList()
GridViewDocuments.DataSource = docs
GridViewDocuments.DataBind()
In the above code, the DocViewList, instantiated as docs, is a list of a class that has all the properties that are needed to fill my GridView, which is named GridViewDocuments here. Once you set the DataSource of your GridView, you can bind any of the source's properties to an item.
Something like:
<asp:LinkButton ID="LinkButton_Title" runat="server" target="_blank"
PostBackUrl='<%# Eval(Request.QueryString["title"]) %>'
or binding them from the RowCreated event:
protected void GridView_OnRowCreated(Object sender, GridViewRowEventArgs e)
{
if(e.Row.RowType == DataControlRowType.DataRow)
{
(e.Row.FindControl("LinkButton_Title") as LinkButton).PostBackUrl = Request.QueryString["title"]))
}
}
Related
I have regular asp.net gridview,and i want to enable editmode in each row,and also without editbutton (like excel grid).
Edited data i want to save to my database by clicking "Post" button outside the grid(one button for whole grid).
How can i reach it?
To achieve this, you are going to have to use ItemTemplates for each column with textboxes in them as the control..
ASP
<asp:TemplateField HeaderText="Heading Title" SortExpression="Heading Title">
<ItemTemplate>
<asp:TextBox ID="tbTextbox" runat="server" Width="65px" Text='<%# Bind("ColumnNameYouWantToView") %>'></asp:TextBox>
</ItemTemplate>
</asp:TemplateField>
After this is set up properly, you will want the post button. You can either put it in the grid or outside the grid. I use both, but here is the one inside the grid as a footer.
ASP
<asp:TemplateField>
<ItemTemplate>
<asp:Button ID="btnView" runat="server" Text="View" OnClick="btnView_Click" Width="40px" />
</ItemTemplate>
<FooterTemplate>
<asp:Button ValidationGroup="UPDATE" ID="btnUpdate" OnClick="btnUpdate_Click" runat="server" Text="Update" Width="50px"></asp:Button>
</FooterTemplate>
<FooterStyle HorizontalAlign="Center" VerticalAlign="Middle" Width="50px" />
</asp:TemplateField>
So far, what I have found that works best is using a foreach statement in your button click. The biggest flaw with this idea is that it will update every single row. It works, but if you only change a single row at a time, it will update all of them. I have my pager set to 10, so 10 rows are always updated (unless you are just searching for a single record and update it, the only that single record is updated).
Code Behind C#
protected void btnUpdate_Click(object sender, EventArgs e)
{
SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["databaseConnection"].ConnectionString);
conn.Open();
//finds the controls within the gridview and updates them
foreach (GridViewRow gvr in gvGridViewName.Rows)
{
string ID = (gvr.FindControl("lblId") as Label).Text.Trim();//finds the control in the gridview
string anotherControl = ((TextBox)gvr.FindControl("tbTextBox")).Text.Trim();//finds the textbox in the gridview
//Your update or insert statements
}
This is how I do it. You can also look into Real World Grids but I haven't had much luck with this as I would always get an error if a textbox was empty. This however, is suppose to be "smart" enough to just update the rows that have been changed, but again, I didn't have much luck of doing it this way. Hope this helps!
I would like to find a GridView Control within a separate class and I am having issues doing so. I even tried placing my code in the aspx.cs page to no avail. I keep getting Object reference not set to an instance of an object. I'm sure there is a simple step I'm missing, but in my research I cannot seem to find anything.
Aspx code
<asp:GridView ID="GridView1" EnableViewState="true"
runat="server"
BackColor="White" BorderColor="#CC9966"
BorderStyle="None" BorderWidth="1px" CellPadding="4" Width="933px"
onrowdatabound="GridView1_RowDataBound"
onrowdeleting="GridView1_RowDeleting"
onrowediting="GridView1_RowEditing"
onrowupdating="GridView1_RowUpdating"
onsorting="GridView1_Sorting"
AllowSorting="true"
AutoGenerateColumns="False"
PersistedSelection="true" onrowcancelingedit="GridView1_RowCancelingEdit">
<EditRowStyle Font-Size="Small" Width="100px" />
<FooterStyle BackColor="#FFFFCC" ForeColor="#330099" />
<Columns>
<asp:TemplateField>
<ItemTemplate>
<asp:LinkButton runat="server" ID="EditLinkButton" CausesValidation="True"
Text="Edit" CommandName="Edit"/>
<asp:LinkButton runat="server" ID="DeleteLinkButton" CausesValidation="False"
Text="Delete" CommandName="Delete"/>
</ItemTemplate>
<EditItemTemplate>
<asp:LinkButton runat="server" ID="UpdateLinkButton" CausesValidation="True"
Text="Update" CommandName="Update"/>
<asp:LinkButton runat="server" ID="CancelLinkButton" CausesValidation="False"
Text="Cancel" CommandName="Cancel"/>
</EditItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
.cs code
protected void Page_Load(object sender, EventArgs e) {
SetDirectory();
System.Web.UI.Page page = (System.Web.UI.Page)System.Web.HttpContext.Current.Handler;
GridView GridViewCopy = (GridView)page.FindControl("GridView1");
Log.WriteLine("SortBindGrid: GridView Row Count: " +
GridViewCopy.Rows.Count, Log.DEBUG_LEVEL.TERSE);
return;
}
I've tried a few variations of using MainContent_GridView for the find to get and Master.FindControl with all the same result.
In one of your comments you state that the GridView isn't on the Master Page, so is it safe to assume that it's on a page that uses a Master Page? And therefore it must be in a ContentPlaceholder control?
The key issue is that FindControl method only looks for direct children (emphasis added):
This method will find a control only if the control is directly contained by the specified container; that is, the method does not search throughout a hierarchy of controls within controls.
So you either need to:
Search for the control within the correct ContentPlaceholder control, rather than from Page.
Loop through each of the Controls in Page.Controls recursively until you find the control you're after.
An example of 2:
private Control FindControlRecursive(Control rootControl, string controlID)
{
if (rootControl.ID == controlID) return rootControl;
foreach (Control controlToSearch in rootControl.Controls)
{
Control controlToReturn =
FindControlRecursive(controlToSearch, controlID);
if (controlToReturn != null) return controlToReturn;
}
return null;
}
Once you've got your control, you should cast it using as and then check for null just in case it's not quite what you were expecting:
var gridView = FindControlRecursively(Page, "GridView1") as GridView
if (null != gridView) {
// Do Stuff
}
Don't get the page from HttpContext if you are already within the page. Instead, is there a control you can use FindControl from? Instead of use page, use:
parentControl.FindControl("GridView1") as GridView;
Instead. There is an issue with finding the grid from the page level, and using a lower level control closer to the grid will have better success.
Brian got it right but he forgot the essential part.
You won't be able to do use his code unless you add this code on top of your HTML-Code of the file where you want to use it.(Page.aspx)
<%# MasterType VirtualPath="~/Master/Site.master" %>
then you can use the code Brian suggested:
GridView grid = this.Master.FindControl("GridView1");
Edit:
If you want to use the gridview from within another class in the same file i would use the following:
Add this to the class created when you make the page
public partial class YourPageName: System.Web.UI.Page
{
public static Gridview mygrid = this.GridviewnameOFYourASPX
...
}
And to your custom class add this in your method
YourPageName.mygrid.(The changes you want to make);
I have a gridview with multiple rows, each has a Update button and I need to pass 2 values when someone clicks on Update button.
Aside from packing the arguments inside CommandArgument separated by commas (archaic and not elegant), how would I pass more than one argument?
<asp:LinkButton ID="UpdateButton" runat="server" CommandName="UpdateRow" CommandArgument="arg_value" Text="Update and Insert" OnCommand="CommandButton_Click" ></asp:LinkButton>
As a note, the values can't be retrieved from any controls on the page, so I am presently not seeking any design solutions.
You can pass semicolon separated values as command argument and then split the string and use it.
<asp:TemplateField ShowHeader="false">
<ItemTemplate>
<asp:LinkButton ID="lnkCustomize" Text="Customize" CommandName="Customize" CommandArgument='<%#Eval("IdTemplate") + ";" +Eval("EntityId")%>' runat="server">
</asp:LinkButton>
</ItemTemplate>
</asp:TemplateField>
at server side
protected void gridview_RowCommand(object sender, GridViewCommandEventArgs e)
{
string[] arg = new string[2];
arg = e.CommandArgument.ToString().Split(';');
Session["IdTemplate"] = arg[0];
Session["IdEntity"] = arg[1];
Response.Redirect("Samplepage.aspx");
}
After poking around it looks like Kelsey is correct.
Just use a comma or something and split it when you want to consume it.
#Patrick's answer is a good idea, and deserves more credit!. You can have as many data items as you want, they are all separated, and can be used client side if necessary.
They can also be added declaratively rather than in code. I just did this for a GridView like this:
<asp:TemplateField HeaderText="Remind">
<ItemTemplate>
<asp:ImageButton ID="btnEmail"
data-rider-name="<%# ((Result)((GridViewRow) Container).DataItem).Rider %>"
data-rider-email="<%# ((Result)((GridViewRow) Container).DataItem).RiderEmail %>"
CommandName="Email" runat="server" ImageAlign="AbsMiddle" ImageUrl="~/images/email.gif" />
</ItemTemplate>
</asp:TemplateField>
In the RowCommand, you do this:
void gvMyView_RowCommand(object sender, GridViewCommandEventArgs e)
{
if (e.CommandName == "Email")
{
var btnSender = (ImageButton)e.CommandSource;
var riderName = btnSender.Attributes["data-rider-name"];
var riderEmail = btnSender.Attributes["data-rider-email"];
// Do something here
}
}
So much cleaner than hacking all the values together with delimiters and unpacking again at the end.
Don't forget to test/clean any data you get back from the page, in case it's been tampered with!
My approach is using the attributes collection to add HTML data- attributes from code behind. This is more inline with jquery and client side scripting.
// This would likely be done with findControl in your grid OnItemCreated handler
LinkButton targetBtn = new LinkButton();
// Add attributes
targetBtn.Attributes.Add("data-{your data name here}", value.ToString() );
targetBtn.Attributes.Add("data-{your data name 2 here}", value2.ToString() );
Then retrieve the values through the attribute collection
string val = targetBtn.Attributes["data-{your data name here}"].ToString();
A little more elegant way of doing the same adding on to the above comment ..
<asp:GridView ID="grdParent" runat="server" BackColor="White" BorderColor="#DEDFDE"
AutoGenerateColumns="false"
OnRowDeleting="deleteRow"
GridLines="Vertical">
<asp:BoundField DataField="IdTemplate" HeaderText="IdTemplate" />
<asp:BoundField DataField="EntityId" HeaderText="EntityId" />
<asp:TemplateField ShowHeader="false">
<ItemTemplate>
<asp:LinkButton ID="lnkCustomize" Text="Delete" CommandName="Delete" CommandArgument='<%#Eval("IdTemplate") + ";" +Eval("EntityId")%>' runat="server">
</asp:LinkButton>
</ItemTemplate>
</asp:TemplateField>
</asp:GridView>
And on the server side:
protected void deleteRow(object sender, GridViewDeleteEventArgs e)
{
string IdTemplate= e.Values["IdTemplate"].ToString();
string EntityId = e.Values["EntityId"].ToString();
// Do stuff..
}
Either store it in the gridview datakeys collection, or store it in a hidden field inside the same cell, or join the values together. That is the only way. You can't store two values in one link.
If you want to pass two values, you can use this approach
<asp:LinkButton ID="RemoveFroRole" Text="Remove From Role" runat="server"
CommandName='<%# Eval("UserName") %>' CommandArgument='<%# Eval("RoleName") %>'
OnClick="RemoveFromRole_Click" />
Basically I am treating {CommmandName,CommandArgument} as key value. Set both from database field. You will have to use OnClick event and use OnCommand event in this case, which I think is more clean code.
Here's how I want the control to work. Click edit on a row in gridview. There's a textbox in one of the columns, I would like it to be blank even though there's data in the database for that column, but when I click update I would like whatever new text the user entered to update the database for that column. It would be one-way databinding, but the other way?
Here's how I did it using an sql datasource with the select,update and delete methods generated.
First, you'll need to make any column that you want to edit like this a template field with an item template and and edit item template:
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False"
DataKeyNames="ID" DataSourceID="SqlDataSource1"
onrowupdating="GridView1_RowUpdating">
<Columns>
<asp:TemplateField HeaderText="City" SortExpression="City">
<ItemTemplate>
<asp:Label runat="server" Text='<%# Eval("City") %>'></asp:Label>
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox runat="server" ID="txtCityEdit" Text=""></asp:TextBox>
</EditItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
Next handle the gridview's on update event:
protected void GridView1_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
//find the value control who's value you want
TextBox tb = (TextBox)GridView1.Rows[e.RowIndex].FindControl("txtCityEdit");
//since we are not using a bound column for city we need to explicitly insert the value
//into the update parameter.
SqlDataSource1.UpdateParameters["City"].DefaultValue = tb.Text;
}
Even if you are using something other than an SQL Datasource this should be the basic solution.
// Find notes textbox
TextBox tb = (TextBox)MyActiveReferrals.Rows[e.RowIndex].FindControl("NotesTextBox");
e.NewValues.Add("Notes", tb.Text);
I used a linq data source.
So in this gridview, there is a column for status and I want to have a drop down list with Pass, Pending, Fail appear when the edit button is clicked. These values are already in a table, so I need to somehow bind from this table to each ddl for every row.
Here is the column from the gridview. As you can see, I would like to just have a label showing when not in edit mode, and a ddl when the edit button is pressed
<asp:TemplateField HeaderText="During Production Status" SortExpression="DuringProductionStatus">
<EditItemTemplate>
<asp:DropDownList ID="ddlStatus" runat="server" datavaluefield="Name"
datatextfield="Name" DataSource="*What goes here?*"> />
</EditItemTemplate>
<ItemTemplate>
<asp:Label ID="lblStatus" runat="server"
Text='I don't understand how to get this from the ddl' />
</ItemTemplate>
</asp:TemplateField>
For clarity's sake, my table is named Status, and the database is named DirectImport
There's a few steps to go through here - none of them are particularly difficult, but they can be a bit fiddly (IMHO). The good news is once you've got this working once, it gets easier to do it again!
I'm assuming you've got a <asp:*DataSource> control on your page - my preference is for an ObjectDataSource but I don't think it matters, I think a SqlDataSource works equally well. I've never tried doing this with GridView.DataSource = MyDataSet in code-behind, so I don't know whether that would work or not, but my assumption is that it wouldn't as you wouldn't get the proper two-way binding that you want. This data source feeds your grid with your main data. The key point here is that your database query must return both the Status text field and the Status id.
So your gridview will now look something like:
<asp:objectdatasource runat="server" id="MainDataSource" ... />
<asp:gridview runat="server" id="MyGridView" DataSourceID="MainDataSource">
<Columns>
<asp:TemplateField HeaderText="During Production Status" SortExpression="DuringProductionStatus">
<ItemTemplate>
<asp:Label ID="lblStatus" runat="server"
Text="<%# Bind('Status') %>" />
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:gridview>
The Text="<%# Bind('Status') %>" is the bit you're missing to get the status text into the grid.
Now add a second data source into your markup that reads in the set of values from the Status table.
<asp:objectdatasource runat="server" id="StatusObjectDataSource" ... />
And add the EditItemTemplate into the GridView, which is bound to the Status DataSource.
<EditItemTemplate>
<asp:DropDownList ID="ddlStatus" runat="server" datavaluefield="StatusID"
datatextfield="Status" DataSourceID="StatusObjectDataSource"
SelectedValue="<%# Bind('StatusId') %>" />
</EditItemTemplate>
The SelectedValue="<%# Bind('StatusId') %>" is what connects up the two datasets so that when you flip a row into Edit mode, the dropdownlist has the correct item already selected, and when you then save it you've got the Status ID to put into your database.
And you're done.
I have used the RowDataBound event. Here is a small code snippet. HTH
you would have an ItemTemplate in your aspx/ascx
<asp:TemplateField HeaderText="Column Headings">
<ItemTemplate>
<asp:DropDownList ID="ddlName" runat="server" Width="150"></asp:DropDownList>
</ItemTemplate>
</asp:TemplateField>
and in your code behind, you will have
protected void grdDataMap_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
DropDownList ddl = (DropDownList)e.Row.FindControl("ddlName");
ddl.DataSource = someList;//the source of your dropdown
ddl.DataBind();
}
}
so when you bind your grid with grdDataMap.Databind (assuming your grid id is grdDataMap), row databound event will be called for each row (including header/footer, and thats the reason you check RowType)
so you can probably decide what controls/columns to hide/show/bind inside this row databound event
In the winforms world I pull my objects from the DB into a List(Of Whatever) and use the list as the datasource.
This also lets me add extra "convenience" fields in the object so that I can populate it with stuff from other tables.
I don't know asp.net at all so if you can do something similar, it might help.
A really quick solution is to create a custom web control for the status dropdown. The control will always contain the same data. When it renders you populate the datasource. When it gets added to the gridview, the data will be in the drop down. Hope that helps!