Hide button in gridview when field is Null - asp.net

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.

Related

ASP.net gridview cant update image

So i'm a newbie in asp.net. I have this college project which need to use update function. I made the update function, its work fine for all columns except for picture's column. Its not updating picture database, and show the previous picture in the gridview. The pictures in the folder already updated but the gridview just show the previous picture (not the updated one). I need your help please thank you :)
this is the gridview aspx code, if update button was clicked, it will redirect to another page.
<div>
<asp:Label ID="Label1" runat="server" Text=""></asp:Label>
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="false">
<Columns>
<asp:TemplateField HeaderText="Images" ItemStyle-Height="50px" ItemStyle-Width="50px" >
<ItemTemplate>
<asp:Image ID="Image1" runat="server" ImageUrl='<%# Eval("pic") %>'/>/>
</ItemTemplate>
</asp:TemplateField>
<asp:BoundField DataField="nama" HeaderText="nama" />
<asp:BoundField DataField="harga" HeaderText="harga" />
<asp:BoundField DataField="stok" HeaderText="stok" />
<asp:TemplateField>
<ItemTemplate>
<asp:Button ID="btnUpdate" runat="server" OnClick="btnUpdate_Click" Text="Update" wID='<%# Eval("Id") %>'/>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
</div>
this is the Page_Load function
public List<Table> getAll()
{
List<Table> watches = (from x in de.Tables select x).ToList();
return watches;
}
public void loadData()
{
GridView1.DataSource = repo.getAll();
GridView1.DataBind();
}
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack) loadData();
}
and redirected to update aspx
<asp:Label ID="Label1" runat="server" Text="Label"></asp:Label>
<br />
<asp:FileUpload ID="pic" runat="server" />
<br />
<asp:TextBox ID="name" runat="server"></asp:TextBox>
<br />
<asp:TextBox ID="price" runat="server"></asp:TextBox>
<br />
<asp:TextBox ID="stok" runat="server"></asp:TextBox>
<br />
<asp:Button ID="btnUpdate" runat="server" Text="Button" OnClick="btnUpdate_Click" />
This is the update function of btnUpdate in update aspx
protected void btnUpdate_Click(object sender, EventArgs e)
{
string ext = System.IO.Path.GetExtension(pic.FileName);
string nama = name.Text;
int harga = Int32.Parse(price.Text);
int stock = Int32.Parse(stok.Text);
Table update = (Table)Session["updateWatch"];
string pict = "..\\Pictures\\Watch Pictures\\" + update.Id + ext;
bool updateStatus = repo.update(update.Id, pict, nama, harga, stock);
if (updateStatus == false) Label1.Text = "fail";
else
{
string subPic = update.pic.Substring(3);
string path = Server.MapPath("~") + subPic;
string savepath = Server.MapPath("~/Pictures/Watch Pictures/");
System.IO.File.Delete(path);
pic.SaveAs(savepath + update.Id + ext);
Response.Redirect("WebForm1.aspx");
}
}
this is the update function in repository
public bool update(int id, string pic, string nama, int harga, int stok)
{
Table updateW = (from x in de.Tables where x.Id == id select x).FirstOrDefault();
updateW.pic = pic;
updateW.nama = nama;
updateW.harga = harga;
updateW.stok = stok;
de.SaveChanges();
if (updateW == null) return false;
return true;
}
this is the code for gridview datasource
public List<Table> getAll()
{
List<Table> watches = (from x in de.Tables select x).ToList();
return watches;
}

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

Gridview taking more time to bind

I am fetching data from stored procedure and showing in the grid view.
My sql query takes max 1 sec to execute but while binding to gridview it takes more time .
In my page only one gridview is present. and the load time of my page is 10 sec :(
so how to increase my loading time.(i searched on google and didn't find any good solution :( )
My Gridview
<asp:GridView ID="gvStatusStatistics" runat="server" AutoGenerateColumns="False"
CssClass="grid" OnRowCreated="gvStatusStatistics_RowCreated">
<Columns>
<asp:TemplateField HeaderText="PNSC_Leads_LeadStatus">
<ItemTemplate>
<asp:HyperLink ID="hlLeadStatus" ForeColor="#000000" runat="server" Text='<%#Eval("TranslatedStatus") %>'
NavigateUrl='<%# string.Concat("~/ViewLeads.aspx?LeadStatusDefinition=", Eval("Status")) %>'
ToolTip="" />
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="PNSC_Leads_NumberOfLeads">
<ItemTemplate>
<asp:HyperLink ID="hlLeadsCount" ForeColor="#000000" runat="server" Text='<%#Eval("Value") %>'
NavigateUrl='<%# string.Concat("~/ViewLeads.aspx?LeadStatusDefinition=", Eval("Status")) %>'
ToolTip="" />
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
protected void gvStatusStatistics_RowCreated(object sender, GridViewRowEventArgs e)
{
Trace.Write("gvStatusStatistics_RowCreated", "Start");
if (e.Row.RowType == DataControlRowType.DataRow)
{
int CellCounter = 0;
foreach (TableCell cell in e.Row.Cells)
{
CellCounter++;
// track which row this is
if (CellCounter % 2 == 0)
{
// change the alternating one background color
cell.CssClass = GridCellAlternating1Css;
}
else
{
// change the alternating zero background color
cell.CssClass = GridCellAlternating0Css;
}
}
}
}
Please help to solve this.
Thanks
below line taking more time
using (IDataReader dataReader = db.ExecuteReader(dbCommand))
{
}

DataGrid and MultiBind

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()) %>'

gridview dynamic image change in imagebutton

I have a gridview containing some data from db, and after a check I want to see a small cross/tick image in each row, due to the result of the check.How can I change the image url dynamically?
You could either use inline statement like
<%#Eval("check").ToString() == "1" ? "images/checked.gif" : "images/unchceked.gif")%>
or use a function to get the result as follows:
<%# getImageUrl(Eval("value")) %>
Public Function getImageUrl(ByVal value As Integer) As String
If value = 0 Then
Return "images/unchceked.gif"
Else
Return "mages/checked.gif"
End If
End Function
<Columns>
<asp:TemplateField>
<ItemTemplate>
<asp:Image ID="check" runat="server" ImageUrl='<%#If(Eval("check") = 1,"images/checked.gif","images/unchceked.gif") %>' />
</ItemTemplate>
</asp:TemplateField>
</Columns>
in form:
<Columns>
<asp:TemplateField>
<ItemTemplate>
<asp:ImageButton ID="check" runat="server" ImageUrl='<%# GetImageUrl(Eval("Check")) %>' />
</ItemTemplate>
</asp:TemplateField>
</Columns>
code-behind:
public string GetImageUrl(object checkObject)
{
if (checkObject!= null)
{
bool check;
bool parsable = bool.Parse(checkObject.ToString(), out check);
check= parsable ? check : false;
return check ? "~/Media/Images/tick.png" : "~/Media/Images/untick.png";
}
return "~/Media/Images/none.png";
}

Resources