DataGrid and MultiBind - asp.net

I'm new to ASP.NET and are struggling with displaying data in a GridView. I got most of it working with help from this forum. Currently I'm trying to build a file name from an ID and a "file extension" from a database, but got stuck. I guess I need to use MultiBind to get this working? My file name is ID + "_tn" + file extension, and this is my code.
<asp:GridView ID="HitGridView" runat="server" onrowdatabound="HitsRowBid">
<Columns>
<asp:TemplateField HeaderText="Street">
<ItemTemplate>
<asp:TextBox ID="Adress" runat="server" width="200" Text='<%# Bind("StreetName") %>'></asp:TextBox>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Image">
<ItemTemplate>
<asp:ImageButton ID="defaultImg" runat="server" ImageUrl='<%# Bind("ImgId") %>'/>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
and in code behind
protected void HitsRowBid(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
ImageButton imgBtn = (ImageButton)e.Row.FindControl("defaultImg");
imgBtn.ImageUrl = "Content/FileUpload/" + imgBtn.ImageUrl + "_tn" + ".jpg";
}
}
But how do I get the file extension that is stored in the database?

I mainly use ListViews, but there are a couple of ways to accomplish this. One way would be to use DataKeys when databinding and retrieve the value by using the row index in the onrowdatabound event. Another option would be to write a helper method in codebehind and call it during databinding, something like:
protected string FormatImagePath(string fileName)
{
string imagePath = Request.ApplicationPath.TrimEnd('/') + "/previews/" + fileName;
FileInfo testFile = new FileInfo(Helpers.BaseSiteFilePath + #"previews\\" + fileName);
if (!testFile.Exists)
{
imagePath = Request.ApplicationPath.TrimEnd('/') + "/images/no_preview.png";
}
return imagePath;
}
Calling it like such:
ImageUrl='<%# FormatImagePath(Eval("PreviewURL").ToString()) %>'

Related

execution of the current web request. Object cannot be cast from DBNull to other types

Please do not down vote. i am new to this site.
i tried myself but repeatedly the same error occurring.
protected void gvDepPayment_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
Label lbl = (Label)e.Row.FindControl("lblDeptName");
DataTable dT = (DataTable)ViewState["DataBounded"];
DataRow[] drows = dT.Select("DepartmentName = '" + lbl.Text + "'");
int Count = 0;
foreach (DataRow item in drows)
{
Count += Convert.ToInt32(item["PaidAmount"]);
}
Label lblPaidAmount = (Label)e.Row.FindControl("lblPaidAmount");
lblPaidAmount.Text = Count.ToString();
}
}
<asp:GridView ID="gvDepPayment" runat="server" AutoGenerateColumns="false"
OnRowDataBound="gvDepPayment_RowDataBound">
<Columns>
<asp:TemplateField HeaderText="Department Name">
<ItemTemplate>
<asp:Label ID="lblDeptName" runat="server" Text='<%#Eval("DepartmentName") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Collection">
<ItemTemplate>
<asp:Label ID="lblPaidAmount" runat="server" Text="0"></asp:Label>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
i want find the Payment list and show it in grid view like Department wise
This error message is caused by your reading the content of the DataRow at the column named PaidAmount, probably there are some null values in the set of rows returned by your query. In this scenario you could use the IsNull method of the DataRow class with the conditional operator. In the case of DBNull.Value you want to add zero to your count.
Count += item.IsNull("PaidAmount") ? 0 : Convert.ToInt32(item["PaidAmount"]);

ASP.Net DropDownList selected value missing

At the beginning I have to say that I tried to find the answer... And yes I'm new in ASP.Net world :)
I would like to use DropDownList in an EditItemTemplate field in GridView. I found I cannot set parametr SelectedValue. It's missing. When I try to set it in code behind it seems to ddlEditPermissions doesn't exists.
<asp:TemplateField HeaderText="opravneni" SortExpression="opravneni">
<edititemtemplate>
<asp:DropDownList ID="ddlEditPermissions" runat="server" DataSource='<%# getPermissions() %>' OnPreRender="ddlEditPermissions_PreRender"/>
</edititemtemplate>
<insertitemtemplate>
<asp:TextBox ID="tbEditPermissions" runat="server" Text='<%# Bind("opravneni") %>'></asp:TextBox>
</insertitemtemplate>
<itemtemplate>
<asp:Label ID="lEditPermissions" runat="server" Text='<%# Bind("opravneni") %>'></asp:Label>
</itemtemplate>
I'm really confused. Could anyone advise me?
You can use RowDataBound of the GridView which gets triggered for every GridViewRow after it was constructed and databound:
protected void gridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow && e.Row.RowState == DataControlRowState.Edit)
{
var ddlEditPermissions = (DropDownList)e.Row.FindControl("ddlEditPermissions");
// bind DropDown manually
ddlEditPermissions.DataSource = getPermissions();
ddlEditPermissions.DataTextField = "Permission_Name"; // presumed text-column
ddlEditPermissions.DataValueField = "Permission_ID"; // presumed id-column
ddlEditPermissions.DataBind();
DataRowView dr = e.Row.DataItem as DataRowView; // you might need to change this type, use the debugger then to determine it
ddlEditPermissions.SelectedValue = dr["Permission_ID"].ToString(); // presumed foreign-key-column
}
}

Hide button in gridview when field is Null

I have a grid view where some of the rows have attached pictures. when I press Button2 I pull information from the sql record, about which folder on the server that has the pictures.
This works already, but I can not get the button to only be visible in the rows that have image folder attached.
I've googled a long time and found different solutions similar to the following, but I can not get it to work.
What am I doing wrong?
<asp:SqlDataSource ID="SqlDSodinRSSfeb" runat="server"
ConnectionString="<%$ ConnectionStrings:herning_brand_dk_dbConnectionString %>"
SelectCommand="SELECT PubDateTime, Melding, Station, PhotoFolder FROM OdinRSS ">
</asp:SqlDataSource>
<asp:GridView ID="GridView14" runat="server" DataSourceID="SqlDSodinRSSfeb"
AutoGenerateColumns="False" Width="500px" OnRowCommand="Button_RowCommand" >
<Columns>
<asp:BoundField DataField="PubDateTime" HeaderText="Tidspunkt" />
<asp:BoundField DataField="Melding" HeaderText="Melding for udkaldet" />
<asp:BoundField DataField="Station" HeaderText="Station" />
<asp:TemplateField HeaderText="Foto" >
<EditItemTemplate>
<asp:TextBox ID="TextBox1" runat="server" Text='<%# Bind("PhotoFolder") %>'></asp:TextBox>
</EditItemTemplate>
<ItemTemplate>
<asp:Button ID="Button2" runat="server" Text="Foto" Visible='<%# Eval("PhotoFolder") != "Null" %>'
CommandName="ButtonClick" CommandArgument='<%# Eval("PhotoFolder") %>' />
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
My .cs
protected void Button_RowCommand(object sender, GridViewCommandEventArgs e)
{
if (e.CommandArgument != null)
{
switch (e.CommandName)
{
case "ButtonClick":
{
int Folder = Convert.ToInt32(e.CommandArgument);
PhotoList(Folder);
}
break;
}
}
}
void PhotoList(int FolderNumber)
{
var imagePaths = Directory.GetFiles(Server.MapPath("PhotoFolder\\" + FolderNumber));
var imageNames = new string[imagePaths.Length];
for (int i = 0; i < imagePaths.Length; i++)
{
imageNames[i] = imagePaths[i].Substring(imagePaths[i].LastIndexOf("\\") + 1);
}
var dt = new DataTable();
dt.Columns.Add("ImageName", typeof(string));
dt.Columns.Add("ImagePath", typeof(string));
foreach (var imgName in imageNames)
{
DataRow dr = dt.NewRow();
dr["ImageName"] = RemoveExtension(imgName);
dr["ImagePath"] = "PhotoFolder/" + FolderNumber + "/" + imgName;
dt.Rows.Add(dr);
}
DataList1.DataSource = dt;
DataList1.DataBind();
}
string RemoveExtension(string imgName)
{
return imgName
.Replace(".jpg", "")
.Replace(".png", "");
}
The sql field "PhotoFolder" is a nvarchar(50). If there is photos for the record, the field has a number from 100 and up, that refares to the folder containing photos. If there are no photo for the record, the field contains "Null"
I have also tried:
<asp:Button ID="Button2" runat="server" Text="Foto" Visible='<%# Eval("PhotoFolder").ToString() != "Null" %>'
But the button is shown in all rows, not just the ones that has a string(number) in "PhotoFolder"
It can be achieved simple in Inline code
<asp:ImageButton ID="ibtnBranchType1" runat="server" ImageUrl='<%# "~/images/" + Eval("branchtype1")+".png" %>' Visible='<%# Convert.ToString(Eval("branchtype1"))=="" ? false : true %>' Height="20px"/>
Here Eval("branchtype1") we are getting value of id from data table like 1, 2, 3 etc. and our image folder consists images like 1.png, 2.png, 3.png etc.,
Visible='<%# Convert.ToString(Eval("branchtype1"))=="" ? false : true %>'
if value doesn't contain any id it will get null. we will compare it with empty string using ternary operator.
Try this.
Markup
Visible='<%# HideEmptyPhotoFolder(Eval("PhotoFolder")) %>'
Code-Behind
protected bool HideEmptyPhotoFolder(object photoFolder)
{
return photoFolder != null && !String.IsNullOrEmpty(photoFolder.ToString());
}
You can simply do that in GridView RowDataBound event.
http://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.gridview.rowdatabound.aspx
As per your question you should write the code for checking the rows containing the image,
you can write the code in RowDatabound event,and set visible property of button to false on that row which doesn't contain image.

Open new dynamic window within gridview dataview?

I have a gridview (called grdSearchResults) that contains links to pdfs. The pdf url's are returned from the database but I'm not sure how to add the url to an imagebutton control within the gridview.
Here's my codebehind:
List<SearchResults> search = _searchRepository.GetFactFileSearchResults(results);
grdSearchResults.DataSource = search;
grdSearchResults.DataBind();
And here's my aspx page code:
<asp:TemplateField HeaderText="FILE TYPE" ItemStyle-HorizontalAlign="Center">
<ItemTemplate>
<asp:ImageButton runat="server" ID="_imgbtnPreview" OnClientClick="<%# Container.DataItem("DownloadUrl") %>" ImageUrl="~/images/fileType_pdf.png" />
</ItemTemplate>
But this thows an error ("The server tag is not well formed") Any idea how to fix this? Thanks
I assume you want to call a javascript function OnClientClick. But you haven't showed us it so it's difficult to help.
You can also set the ImageButton's ImageUrl in RowDataBound (which i normally prefer):
protected void grdSearchResults_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
DataRowView rv = (DataRowView) row.DataItem;
ImageButton imgbtnPreview = (ImageButton)e.Row.FindControl("_imgbtnPreview");
imgbtnPreview.ImageUrl = rv.Row.Field<String>("DownloadUrl");
}
}
Your OnClientClick should be using single quote in the outer
OnClientClick='<%# Container.DataItem("DownloadUrl") %>'
And the image can be
<asp:Image runat="server" ID="x" ImageUrl='<%# String.Format("~/{0}", Eval("ImageUrl")) %>' />

GridView: convert data before bindind to GridView

My GridView using following data binding syntax to bind data.
I hope do data conversion before it is really bound to GridView. For example, if the VendorID int property (I use a List as data source) is 0, I wish showing empty string on that field.
What kind of event I could exploit? And if you could suggest any code sample?
Thanks a lot.
<asp:TemplateField HeaderText="Vendor ID">
<ItemStyle Width="1%" BorderColor="#efefef" BorderWidth="1px" />
<ItemTemplate>
<asp:Label runat="server" ID="lblNo" Text='<%# Bind("VendorID") %>'></asp:Label>
</ItemTemplate>
<HeaderStyle BorderColor="#efefef" />
</asp:TemplateField>
Gridview's RowDataBound Event can be use for this.
void GridView1_RowDataBound(Object sender, GridViewRowEventArgs e)
{
if(e.Row.RowType == DataControlRowType.DataRow)
{
// do wat ever u like to do here.
// formating, checking, changing data, etc....
e.Row.Cells[1].Text = "<i>" + e.Row.Cells[1].Text + "</i>";
}
}
hi you can use following code in RowDataboundEvent
if (DataBinder.Eval(args.Row.DataItem, "VendorID").ToString() == "0")
{
((Label)args.Row.FindControl("lblNo")).Text = "";
}
else
{
((Label)args.Row.FindControl("lblNo")).Text = DataBinder.Eval(args.Row.DataItem, "VendorID").ToString();
}

Resources