What I'm trying to do here is have a datagrid show a list of files on the server which the user can click on to download, or open. The list populates with the files just fine, I get a whole list of all the pdf files in the folder. When I go to click on them in the datagrid, the link is directed to the application root directory and not to the proper folders. How do I tell a datagrid hyperlink column where to go?
C# code behind:
DirectoryInfo dir = new DirectoryInfo(Server.MapPath("~") + "/Assets/reports/");
gridList.DataSource = dir.GetFiles("*.pdf");
gridList.DataBind();
asp
<asp:DataGrid runat="server" id="gridList" Font-Name="Verdana"
<Columns>
<asp:HyperLinkColumn DataNavigateUrlField="Name" DataTextField="Name"
HeaderText="File Name"/>
</Columns>
</asp:DataGrid>
I tried placing this in:
NavigateUrl = '<%# "~/Assets/reports/" + Eval("Name") %>'>
but I get a "databinding expressions are only supported on objects that have a databinding event." error
Here you go.
<asp:HyperLinkColumn DataNavigateUrlField="Name"
DataTextField="Name"
HeaderText="File Name"
DataNavigateUrlFormatString="~\examfilemanager\{0}" />
Found it here.
asp.net DataGrid file structure and linking back to it
Related
I have a class (POCO) that has an Image property. I use a List<> of this class as the datasource for a gridview control. Most of the properties are grabbed from the database. However, I am dynamically generating a barcode (System.Drawing.Image) in my code behind and populating the Image property in the POCO with the result prior to databinding. It is NOT possible for me to store the images on the database or the filesystem. How do I go about displaying the barcodes in the Gridview control? When I try, nothing shows and the images generate 404 errors. The code for the gridview is:
<asp:GridView runat="server" ID="gvInventoryDetail" CssClass="centerpage"
style="width: 700px;" ItemType="DisplayModels.InventoryDetailItem"
DataKeyNames="InventoryId" AutoGenerateColumns="False"
AllowPaging="True" PageSize="11" ShowHeaderWhenEmpty="True">
<Columns>
<asp:BoundField HeaderText="Barcode" DataField="Barcode"/>
<asp:TemplateField HeaderText="Image">
<ItemTemplate >
<asp:Image ID="BarcodeImage" runat="server"
Height="150px" Width="80px" />
</ItemTemplate>
</asp:TemplateField>
<asp:BoundField HeaderText="Comments" DataField="Comments"/>
<asp:BoundField HeaderText="Status" DataField="Status"/>
<asp:BoundField HeaderText="Broken?" DataField="IsBroken"/>
</Columns>
<SelectedRowStyle BackColor="#89d8f6" Font-Bold="True"/>
</asp:GridView>
Any help is MUCH appreciated!
I had a similar issue when generating pie charts using another 3rd party project.
What I did was the following:
Keep the Image Tag in your Grid.
Set that Image Tag to call an ASPX Page in your site, passing what ever params you need on the URL to generate the barcode image.
In that new ASPX do the following
response.clear()
response.binarywrite() of the image.
If you browse that URL you will see the image in the browser, which means, that URL would also show the image in your Image Tag in your grid.
I'm trying to export the contents of an ASP.NET gridView control to an Excel spreadsheet. To do this I've been using the code on this page.
When it gets to the RederControl(hw) line though my code blows up. I get an error like:
GridView must be placed inside a form tag with runat=“server” even after the GridView is within a form tag
To solve this I found this answer. However the main answer does not work and I think it is because my code is in an .ascx user control. With that in mind I tried the solutions in the second highest rated answer.
This time I get error relating to the DataControlLinkButtons similar to the title of this question.
My gridview contains hyperlinks inside in the cells of one column. I tried to remove them from their parent control prior to rendering with the following code (as per the second answer on that page)
List<int> gridIndexes=new List<int>();
for (int i = 1; i < gdvDataGroups.Controls[0].Controls.Count-1; i++)
{
gridIndexes.Add(gdvDataGroups.Controls.IndexOf(gdvDataGroups.Controls[0].Controls[i].Controls[8].Controls[1]));
gdvDataGroups.Controls.Remove(gdvDataGroups.Controls[0].Controls[i].Controls[8].Controls[1]);
}
but it didn't work for me and I got the same error.
Any ideas of how to approach this?
The gridView is as follows (with only the relevant 9th column included):
<asp:GridView ID="gdvDataFiles" SkinID="MediumSpace" runat="server" AutoGenerateColumns="False"
ShowHeader="true" Width="100%" OnPageIndexChanging="gdvDataFiles_PageIndexChanging"
AllowPaging="True" PageSize="20">
<Columns>
<asp:TemplateField HeaderText="Details" ItemStyle-Width="80px" ItemStyle-HorizontalAlign="Center">
<ItemTemplate>
<asp:HyperLink ID="HyperLink1" runat="server" Text='<%# Eval("RequestPKID") == null ? "Not available" : "View" %>'
NavigateUrl='<%# Eval("RequestPKID") == null ? "" : Eval("RequestPkid", "../Pages/BOLoadDetails.aspx?fileid={0}") %>'
Style="padding-top: 4px; display: block" />
</ItemTemplate>
</asp:TemplateField>
</Columns>
<EmptyDataTemplate>
No data file loads found
</EmptyDataTemplate>
</asp:GridView>
Ok turns out that I needed to disable the sorting on the grid prior to rendering the spreadsheet. I think it was the sort control buttons that were causing the problem.
I am new to ASP.net thing, and i have some question regarding postback.
I have a Senario like this:
1) I have a grid on web with a panel inside.
2) I "Insert" the panel with a Web User Control by calling this
Control ctlControl;
ctlControl = LoadControl("~/UserControls/ChequeCreation.ascx");
pnlTransaction.Controls.Add(ctlControl);
3)The Web User Control providing two button. One is "update" and one is "reset".
Problem is like here:
What i wanted to achieve is when press the "update" button, it will update something back to my DB? But seem after i press the button "Update" or "Reset". The web user control is gone or missing. For my guest is because of the postback issues? Is that correct?
I tried if(!postback) still its doesn't work.
How am i going to overcome this? I already scratching my head about a day?
Thanks you so much.
Regards
LiangCk:
PS:Sorry for my english level, and please dont hesitate to voice out my error or mistake.
well you can convert any of your data columns to template column and then drag and drop your web user control to it
this will result in something like the following code check where "uc1:webUserControle1" is located in the code
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" DataKeyNames="ID" DataSourceID="SqlDB">
<Columns>
<asp:TemplateField HeaderText="ID" SortExpression="ID">
<EditItemTemplate>
<asp:Label ID="Label1" runat="server" Text='<%# Eval("ID") %>'></asp:Label>
</EditItemTemplate>
<ItemTemplate>
<asp:Label ID="Label1" runat="server" Text='<%# Bind("ID") %>'></asp:Label>
<uc1:webUserControle1 ID="WebUserControle1_1" runat="server" />
</ItemTemplate>
</asp:TemplateField>
<asp:BoundField DataField="name" HeaderText="name" SortExpression="name" />
</Columns>
</asp:GridView>
if you are using AJAX, try add updatepanel on your UCT design page
ASP.NET will not preserve a dynamically added user control between postbacks. This is why it is dissapearing. You will need to add the control each time the page is created. However you will need to add it when the control tree is being initialized and restore the original control ID if you want your events to fire. These links provide a full explanation https://web.archive.org/web/20210330142645/http://www.4guysfromrolla.com/articles/092904-1.aspx and http://avinashsing.sunkur.com/2011/02/24/dynamic-controls-viewstate-and-postback/
You have to Every Time Reload the user control on Page_Init or
Page_Load. Then you can get the Button Click Event and After tha User
Control will not lost.
private void LoadUserControl(){
string controlPath = LastLoadedControl;
if (!string.IsNullOrEmpty(controlPath)) {
PlaceHolder1.Controls.Clear();
UserControl uc = (UserControl)LoadControl(controlPath);
PlaceHolder1.Controls.Add(uc);
}
}
protected void Page_Load(object sender, EventArgs e) {
LoadUserControl();
}
I have uploaded files to the server using AsyncFileUpload. How can I display the existing files from the folder using asp.net web forms.? I would like to provide a link to the word document to open the file or save it. I couldn't find any example online. Please let me know. Thanks.
Sample code:
Markup:
<asp:gridView runat="server" id="grid" >
<columns>
<asp:HyperLinkColumn DataTextField="Name" DataNavigateUrlField='<%#Eval(Server.MapPath("FullName")) %>' Target="_blank" />
</columns>
</asp:GridView>
Code behind:
DirectoryInfo dirInfo = new DirectoryInfo(Server.MapPath("YourDirectory"));
FileInfo [] files = dirInfo.GetFiles();
grid.DataSource=files;
grid.DataBind();
You would need to simply get the list of files in that directory using Directory.GetFiles (http://msdn.microsoft.com/en-us/library/07wt70x2.aspx) and then display a suitable list using a gridview or repeater etc.
I'm trying to delete a record from Gridview1 at the same time delete the corresponding image file off the server in a single click. (Each row in Gridview1 has an associated image file on the server.)
To delete the record, I'm using asp:CommandField showDeleteButton="true" along with a sqlDataSource's DELETE statement.
During that process, I'm also using GridView1's "onRowDeleting" event to delete the corresponding image file off the server.
Here's what it does, with the code I have below:
The record indeed gets deleted,
The file on the server does not,
There are NO errors thrown (since I guess that it's not finding the file, and this is the expected behavior).
Also consider:
I've already set up and tested a much simpler "see if files can actually be deleted off the
server" test before I started development on the Gridview. Since our files are on a hosting
company server, I wanted to test for any permissions issues.
Whereby:
Enter the fileName and extension into a text box ("myImage.jpg")
Click the button that uses the File.Delete method
WhaaLa - the file is gone from the server.
However, I can't get the file to go away with my new setup.
Here's the code:
<asp:GridView ID="GridView1" runat="server" AllowSorting="True" AutoGenerateColumns="False" DataKeyNames="libraryID"
DataSourceID="SqlDataSource1" Width="800px" onrowdeleting="deleteImageFromServer" CssClass="gridViewSmallText"
OnDataBound="rowCount">
<Columns>
<asp:CommandField ShowDeleteButton="True" />
<%--A link that goes to the uploadPage to upload a new version of the image--%>
<asp:HyperLinkField runat="server" HeaderText="SKU (Click to Update)" DataTextField="sku" DataNavigateUrlFields="sku" SortExpression="sku" DataNavigateUrlFormatString="graphicUpload.aspx?sku={0}" >
</asp:HyperLinkField>
<asp:TemplateField HeaderText="Image" SortExpression="imagePath">
<ItemTemplate>
<%--Pull the imagePath column from the database here-it also includes the image file --%>
<asp:Image ID="merchImage" runat="server" Height="100px" ImageUrl='<%# "http://www.ourcompanysite.net/" + DataBinder.Eval(Container.DataItem, "imagePath") %>' /><br />
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="View Full Size">
<ItemTemplate>
<%--A link to view the image in it's full size in a new browser window--%>
<asp:HyperLink ID="fullSizeHyperlink" runat="server" NavigateUrl='<%# "http://www.leadingjewelersguild.net/" + DataBinder.Eval(Container.DataItem, "imagePath") %>' Text="View" Target="_blank" />
</ItemTemplate>
</asp:TemplateField>
<asp:BoundField DataField="DateUpdated" </asp:BoundField>
<%---some date stuff here--%>
<asp:BoundField DataField="DateCreated" HeaderText="First Uploaded" SortExpression="DateCreated" >
</asp:BoundField>
</Columns>
</asp:GridView>
Code behind:
protected void deleteImageFromServer(object sender, GridViewDeleteEventArgs e)
{
// I read from GridViewGuy.com that you're supposed to reference the row item via e.Values
string imageToDelete = e.Values["sku"] + ".jpg";
//I pulled the value of "imageToDelete" into a lable just to see what I was getting
//during the "onRowDeleting" and it reported back .jpg instead of the full file name
//myImage.jpg, so I guess this is the crux of my problem.
string image = Server.MapPath("/images/graphicsLib/" + imageToDelete);
string image = Server.MapPath("e:\\sites\\oursite\\files\\images\\graphicsLib\\" + imageToDelete);
if (File.Exists(image))
{
File.Delete(image);
}
//at this point the record from GridView1 is gone, but the file on server remains.
}
I think part of your problem may be that in order for e.Values["sku"] to contain a value, it has to be bound first. I don't think HyperlinkField binds its data (I could be wrong on that though so don't quote me)
First try adding a <asp:BoundField DataField="sku" Visible="false" /> in your column list. or change the HyperLinkField to TemplateField and explicitly bind the sku '<%#Bind("sku")%>'
If that doesn't work you can try changing DataKeyNames="libraryID" to DataKeyNames="libraryID,sku". You should be able to get the value out of e.Keys["sku"], or e.Values["sku"].
After you started development using the GridView control, have you verified that the deleteImageFromServer method is being called by setting a breakpoint in there?
And that imageToDelete is being set correctly?
After breaking into it, look at the 'watch' values for 'sender' and 'e'. Drill down into those to see what kind of objects they are and what values they hold.
Sometimes you have to traverse the object hierarchy in the GridVied control to get to the right object.