ASP.NET GridView CommandField Update/Cancel does not wrap - asp.net

My question is on the ASP.NET GridView control. I am using a CommandField in the Columns tag as seen below.
<asp:CommandField ShowEditButton="True" HeaderStyle-Width="40px" UpdateText="Save" ButtonType="Link" HeaderStyle-Wrap="true" ItemStyle-Wrap="true" ItemStyle-Width="40px"/>
What renders is the shown in the following image (after I click on the Edit button).
As you can see I am trying to have the Cancel link show up a new line and my question is how do you do what? If I change the ButtonType="Link" to ButtonType="Button", I get it rendering correctly as shown below.
alt text http://i38.tinypic.com/2pqopxi.jpg
I've tried Google already and maybe I'm not searching on the right tags but I couldn't see this one addressed before.

If you use a template field it will give you complete control over the look of your page, but it requires that you use the CommandName and possible CommandArgument properties, and also using the GridView's OnRowCommand.
The aspx page:
<asp:GridView id="gvGrid" runat="server" OnRowCommand="gvGrid_Command">
<Columns>
<asp:TemplateField>
<ItemTemplate>
Some Stuff random content
<br />
<asp:LinkButton id="lbDoIt" runat="server" CommandName="Cancel" CommandArgument="SomeIdentifierIfNecessary" />
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
The code behind:
protected void gvGrid_Command(object sender, GridViewCommandEventArgs e)
{
if(e.CommandName=="Cancel")
{
// Do your cancel stuff here.
}
}

Don't use a command field, use a TemplateField and put your command button in that with a line break (br) before it like you want.

Related

Asp.net gridview edit without editbutton

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!

Multiple command in one linkbutton control

I'm new to asp.net development. I would like to ask if it is possible for one link button to have two or more commands?
What I want to happen is that my link button should be able to handle the edit and update commands. Once i click the link in my grid view, it will show the data on its respective controls (i.e textbox for name will have the data of what I clicked) then once I edit any data on the textbox and click the same link it will update and save in the database.
<asp:TemplateField HeaderText="ID">
<ItemTemplate>
<asp:LinkButton ID="lnkEdit" runat="server" CommandArgument='<%#Eval("ID")%>' CommandName="Update"
HeaderText="ID" SortExpression="ID" Text='<%#Eval("ID")%>'>
</asp:LinkButton>
</ItemTemplate>
</asp:TemplateField>
Thanks in advance. Please help!. :)
Its not possible to have multiple commandname for one linkbutton,but when you click linkbutton for editing you can change commandname to "Update".I think this will solve your problem.For changing the commandname for linkbutton refer to this link.
You don't need to create two commands.
First set command name to Edit. Hence on clicking it. It will show data in controls.
Also in click event set command name to Update.
And after updating again set command name to Edit.
Write click event code like this.
if(CommandName=="Edit")
{
//Fill Value in controls
// Set CommandName to Update
}
else if(CommandName=="Update")
{
// Update value in database
// Set command name to Edit
}
Alternatively you can use two linkbuttons with one visible at a time.
Hope this help.
Hi Jenny use code like this:-
<asp:TemplateField HeaderText="ID">
<ItemTemplate>
<asp:LinkButton ID="lnkEdit" runat="server" CommandArgument='<%#Eval("ID")%>' CommandName="Update" Onclick="lnkEdit_Click"
HeaderText="ID" SortExpression="ID" Text='<%#Eval("ID")%>'>
</asp:LinkButton>
</ItemTemplate>
</asp:TemplateField>
In aspx.cs Page write code like below:-
protected void lnkEdit_Click(object sender, EventArgs e)
{
LinkButton btn = (LinkButton )sender;
int Id = Convert.ToInt32(btn.CommandArgument.ToString());
if(btn.CommandName=="Edit")
{
// Write here code for edit
btn.CommandName="Update";
}
else if(btn.CommandName=="Update")
{
// Write here code for Update
btn.CommandName="Edit";
}
}
Hope this help.

Using hyperlink with querystring for gridview row

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"]))
}
}

Redirect to specific page when a gridview buttonfield is clicked

I have two fields in my gridview. One is a field with a date range and one of them is a buttonfield. I want to make it so that when a button is clicked, it will redirect them to a specific page with a formatted string similar to how it's done when a hyperlinkfield is clicked as such:
DataNavigateUrlFormatString="ProductInfo.aspx?ProductID={0}"
However, I don't want to use the other field's value(the date range). I want to use the primary key of the record which is "SundayOfWeek". The user wants a button rather than a hyperlink. Is there a way I can do the same thing with a button?
Try using this type of column instead of a ButtonField:
<Columns>
<asp:HyperLinkField
DataTextField="ProductName"
HeaderText="Product Name"
SortExpression="ProductName"
DataNavigateUrlFields="ProductID"
DataNavigateUrlFormatString="ProductInfo.aspx?ProductID={0}" />
</Columns>
Sure, one of many ways is this:
<columns>
<asp:templatefield headertext="Button">
<itemtemplate>
<asp:Button id="btnRedirect"
Text= "Click me"
CommandArgument='<%#Eval("SundayOfWeek")%>'
OnClick="DoRedirect"
runat="server"/>
</itemtemplate>
</asp:templatefield>
</columns>
protected void DoRedirect(object sender, EventArgs e)
{
Button theButton = sender as Button;
Response.Redirect("Newpage.aspx?ID="+theButton.CommandArgument);
}
If you don't want to use the date-range field, you should use another column as DataNavigateUrlField:
DataNavigateUrlField="KeyField"
DataTextField="DateField"
DataNavigateUrlFormatString="ProductInfo.aspx?ProductID={0}"
If you don't want to use a HyperLinkColumn, you should use a TemplateField and add a Button:
<asp:TemplateColumn>
<input type="button" onclick="location.href='ProductInfo.aspx?ProductID=<%#Eval("KeyField")%>'" value='<%#Eval("DateField")%>'' />
</asp:TemplateColumn>

Using FindControl to get GridView in a Content Page

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);

Resources