I am using the following code to bind image from the database to my asp:Image control in the RadGrid Mastertable. However I am getting a null reference exceptionon the line " iP.ImageUrl = "~/StreamImage.ashx?Id=" + user;" and I am not able to understand why is it giving me that
Here is the code:
<asp:Image ID="iPhoto1" runat="server" AlternateText="Profile Picture"
/>
protected void btnSearch_Click(object sender, EventArgs e)
{
var data = ss.qStudSearch(Common.GetValue(txtName.Text),
Common.GetValue(txtResearch.Text), currUser.iProgramID);
rgSearch.DataSource = data;
rgSearch.DataBind();
foreach (GridDataItem d in rgSearch.MasterTableView.Items)
{
int user = Convert.ToInt32(d.GetDataKeyValue("upid"));
var pix = ss.GetPics(user);
Image iP =
(Image)rgSearch.MasterTableView.FindControl("iPhoto1");
if (pix != null)
{
iP.ImageUrl = "~/StreamImage.ashx?Id=" + user;
}
else
{
iP.ImageUrl = "~/images/no_image.jpg";
}
}
}
The getpics method retrieves the images from the database and it is retrieving it properly as I checked it by debugging. However I am not able to assign it to the asp:Image control.. Can someone help me with this?
It is likely that either iP is null, or user is null. Put a breakpoint before the assignment of iP.ImageUrl and inspect the items to see which one is null.
You can bind directly using binary image column but it's got slow performance with the data:
<telerik:GridBinaryImageColumn DataField="image" HeaderText="Photo" AllowFiltering="false"
UniqueName="LogoView" ImageAlign="NotSet" ImageHeight="80px" ImageWidth="80px"
ResizeMode="Fit" DataAlternateTextField="image">
<HeaderStyle Width="10%" />
</telerik:GridBinaryImageColumn>
Related
I'm doing a C# 3-tier project about pets
On load of the first webform I make a query to the database and get the data of all pets (id, name, photo) as a List to be shown as cards with images in HTML, I'm using Materialize by the way, I leave this link as example http://materializecss.com/cards.html
My code behind (Pets.aspx.cs) is this
protected void Page_Load(object sender, EventArgs e)
{
if(!IsPostBack)
{
NegPet negPet = new NegPet();
StringBuilder sbHtml = new StringBuilder();
List<EntPet> listEntPet = negPet.getAllPet(5); //5 is the user code (get all pets from user 5)
if (listEntPet.Count > 0)
{
foreach (EntPet entPet in listEntPet)
{
sbHtml.Append("<div class=\"col s6 m4\">");
sbHtml.Append("<div class=\"card\">");
sbHtml.Append("<div class=\"card-image\">");
sbHtml.Append("<img src=\"http://www.dogzone.com/images/breeds/beagle.jpg\" alt=\"\" class=\"circle responsive-img\" />");
sbHtml.Append("<asp:LinkButton id=\"lb_"+ entPet.Id_pet + "\" runat=\"server\" CommandArgument='<%# Eval(\""+ entPet.Id_pet + "\") %>')");
sbHtml.Append("\" click=\"updatePet_Click\" class=\"btn-floating halfway-fab waves-effect waves-light red\"><i class=\"material-icons\">edit</i></a>");
sbHtml.Append("</div>");
sbHtml.Append("<div class=\"card-content\">");
sbHtml.Append("<span class=\"card-title\">");
sbHtml.Append(entPet.Name_pet);
sbHtml.Append("</span>");
sbHtml.Append("</div>");
sbHtml.Append("</div>");
sbHtml.Append("</div>");
}
} else
{
sbHtml.Append("<h2>No pets found</h2>");
}
galPet.Controls.Add(new Literal { Text = sbHtml.ToString() });
}
}
Where galPet is a
<asp:PlaceHolder ID="galPet" runat="server" />
This code returns me all the "Id" and "Name" of "Pets" and sets it in the HTML design that I want, similar to a gallery. The problem comes when I try to get to the event onClick="updatePet_Click" apparently it never reaches it's method behind
public void updatePet_Click(Object sender, EventArgs e)
{
LinkButton btn = (LinkButton)(sender);
string yourValue = btn.CommandArgument.Substring(3);
ClientScript.RegisterStartupScript(this.GetType(), "myalert", "alert('" + yourValue + "');", true);
}
What I'm trying to do with this code is retrieve the ID from the clicked asp:LinkButton so I can use it in code behind
I also tried changing the event to "OnClick" but I got this error when tried to click it
Pets.aspx:24 Uncaught ReferenceError: updatePet_Click is not defined
at HTMLUnknownElement.onclick (Pet.aspx:24)
I would like to know how to retrieve the ID to work it in the code behind or if there is another way to pass my list to the HTML design where I can get the clicked ID easier. Thanks
I am using Syncfusion tools to generate a graph dynamically from the data grid. The grid consists of multiple rows and each row has a checkbox for selection. The purpose of the checkbox is to select the entire row data and include that on the graph and grid in the word report. Upon the checkbox selection of a particular row in a grid, the data in that grid needs to be on the graph. Currently, all the data points in the grid are displayed and I am trying to change the logic by adding a condition to pull the data on the graph conditionally. Can someone please help me figure out the logic to get the data on the graph on checkbox selection only. I have researched a lot with no luck yet.
The X-axis: Emphasis area
Y-axis: Incidents
Here’s the code:
private void HandleRecordTypeQ3(int r)
{
PerformanceMeasureDataItem dataItem = reportData.PerformanceMeasureDataList[rCount + q3Count];
q3Count++;
var emphArea = data.Rows[r][RespnseColumnIndex].ToString();
var abbr = data.Rows[r][AbbrColumnIndex].ToString();
var targetCrash = data.Rows[r][TargetCrashtypeColumnIndex].ToString();
var isExluded = data.Rows[r][IsExcludedColumnIndex].ToString();
isExluded = String.IsNullOrEmpty(isExluded) ? "N" : isExluded;
var isGraph = data.Rows[r][IsGraphColumnIndex].ToString();
isGraph = String.IsNullOrEmpty(isGraph) ? "N" : isGraph;
dataItem.Criteria = emphArea;
dataItem.Abbr = abbr;
dataItem.TargetCrashType = targetCrash;
dataItem.IsIncludedinReport=isInluded.Equals("False", StringComparison.OrdinalIgnoreCase) ? false : true;
dataItem.IsGraphData = isGraph.Equals("N", StringComparison.OrdinalIgnoreCase) ? false : true;
for (int i = 0; i < dataItem.Incidents.Count; i++)
{
var rateOfseriousInjuries = data.Rows[r][NumOfFatalitesColumnIndex + i] != null ? data.Rows[r][NumOfFatalitesColumnIndex + i].ToString() : "0";
IncidentInformation currentIncident = dataItem.Incidents[i];
currentIncident.RateOfSeriousInjury = ConvertToDouble(rateOfseriousInjuries);
}
Thanks,
Dimpy
I think you are struggling with passing current record values to server-side.
Since there is an OnServerRowSelected Events which helps to display the selected records on the server side. The below table explains how to display the selected records from the grid to server side.
Default.aspx
<ej:grid id="FlatGrid" runat="server" allowpaging="True" AllowSelection="True" OnServerRowSelected="FlatGrid_ServerRowSelected" Selectiontype="Multiple">
<ClientSideEvents Create="create" ActionComplete="complete" RecordClick="recordClick" />
<Columns>
<ej:Column HeaderTemplateID="#headerTemplate" Template="True" TemplateID="#checkboxTemplate" TextAlign="Center" Width="90" />
<ej:Column Field="EmployeeID" HeaderText="Employee ID" Width="110"></ej:Column>
<ej:Column Field="ShipCity" HeaderText="ShipCity" Width="90" />
</Columns>
</ej:grid>
Default.aspx.cs
protected void FlatGrid_ServerRowSelected(object sender, GridEventArgs e)
{
}
From the Server side, the selected particular record can be displayed as a graph dynamically. I hope this will be helpful to you to get the data on the graph dynamically from the server side.
I am using webforms model binding on EF6 code first project. I have a page that was working perfectly. It stopped working with no apparent reason. The insert method is not called anymore. I have another insert page and it works perfectly still. Anyone know of anything that would cause this?
Here is some of the markup that it is using.
<asp:FormView runat="server" ID="fvTour"
ItemType="CommonInterface.Tour" DefaultMode="Insert"
InsertItemPosition="FirstItem" InsertMethod="InsertItem"
OnItemCommand="ItemCommand" RenderOuterTable="false">
Code behind
public void InsertItem()
{
using (_db)
{
FileUpload picUpload = (FileUpload)fvTour.FindControl("fuploadTour");
if (picUpload == null || !picUpload.HasFile) return;
var item = new CommonInterface.Tour();
item.MemberID = (int)Session["MemberID"];
item.FID = LoginBLL.GetFID(item.MemberID);
item.TourSubmitDate = DateTime.Now;
item.PID = null;
item.TourState = ((DropDownList)fvTour.FindControl("ddlState")).SelectedItem.Text;
item.TourCounty = ((DropDownList)fvTour.FindControl("ddlCounties")).SelectedItem.Text;
item.TourLayout = ((DropDownList)fvTour.FindControl("ddlLayout")).SelectedItem.Text;
item.TourType = ((DropDownList)fvTour.FindControl("ddlType")).SelectedItem.Text;
TryUpdateModel(item);
if (ModelState.IsValid)
{
// Save changes
_db.Tours.Add(item);
_db.SaveChanges();
Response.Redirect("Default");
}
}
}
Edit 2:
Try to use OnItemCommand and see if that works. Set OnItemCommand="ItemCommand" back to your markup and try the following on code behind:
public void ItemCommand(object sender, FormViewCommandEventArgs e)
{
if (e.CommandName == "Insert")
{
InsertItem();
}
}
Make sure that the button you press has a CommandName="Insert" attribute set.
You should be able to set a breakpoint on this method at least. Then you can see if the button fires an event at all.
I was trying to output a single List variable that retrieves data from database via a CodeBehind code to a text field in ASPX:
<asp:TextBox ID="TBCluster" runat="server" CssClass="textbox"></asp:TextBox>
C# is used and the code goes something like this:
public List<shuffleDataList> pullShuffledData(SqlDataReader rdr)
{
List<shuffleDataList> callList = new List<shuffleDataList>();
if (rdr != null)
{
if (rdr.HasRows)
{
while (rdr.Read())
{
callList.Add(new shuffleDataList()
{
cluster = rdr.IsDBNull(5) ? null : rdr.GetString(5),
});
}
}
else
{
Response.Write("<script>alert('the data is null')</script>");
return null;
}
}
return callList;
}
The retrieval of cluster field will occur after a user clicks on a particular button and so my passing the variable goes into like the following:
protected void shuffle_Click(object sender, EventArgs e)
{
getdata();
TBCluster.Text = new shuffleDataList().cluster;
}
However nothing is displayed on the textfield. On the same query, I can display the data on a datagrid view but not on a text field? Any ideas why is this occuring?
Thank you
You don't actually appear to be calling your function. Also, since a Text property is generally a string.. you won't be able to assign a list to it (with any meaningful result). Therefore, I will make a heap of assumptions about your code.. and give you this:
var list = pullShuffledData(someReaderHere);
if (list != null)
TBCluster.Text = string.Join(", ", list.Select(x => x.cluster));
I have finally solved my issue:
string cluster = string.Empty;
DataSet ds = new DataSet();
List<shuffleDataList> list = pullShuffledData(rdr);
foreach(shuffleDataList item in list)
{
cluster = item.cluster;
}
TBCluster.Text = cluster;
It was supposed to be displayed early on but this gridview seems to be clearing the value of pullShuffledData once assigned
//gridviewShuffle.DataSource = pullShuffledData(rdr);
//gridviewShuffle.DataBind();
after commenting out, the cluster value finally appeared on text box. thanks
I have dynamically created hidden input controls in a C# code-behind file, and then populated their values with JavaScript. I now want to access these variables in C#.
Firebug shows that the values do change with JavaScript, but I'm getting the original values back in the code behind. Any insight would be much appreciated.
JavaScript:
function injectVariables(){
var hidden = document.getElementById("point1");
hidden.value = 55;
var hidden2 = document.getElementById("point2");
hidden2.value = 55;
var hidden3 = document.getElementById("point3");
hidden3.value = 55;
alert("values changed");
}
ASPX:
<asp:Button OnClick="Update_PlanRisks" OnClientClick="injectVariables()" Text="updatePlanRisks" runat="server" />
C#:
protected override void CreateChildControls()
{
base.CreateChildControls();
int planId = Convert.ToInt32(Request.QueryString.Get("plan"));
planRisks = wsAccess.GetPlanRiskByPlanId(planId);
foreach (PlanRisk pr in planRisks)
{
HtmlInputHidden hiddenField = new HtmlInputHidden();
hiddenField.ID= "point" + pr.Id;
hiddenField.Name = "point" + pr.Id;
hiddenField.Value = Convert.ToString(pr.Severity);
this.Controls.Add(hiddenField);
}
}
protected void Update_PlanRisks(object sender, EventArgs e)
{
foreach (PlanRisk pr in planRisks)
{
int planRiskId = pr.Id;
string planRiskName = "point" + pr.Id;
HtmlInputHidden hiddenControl = (HtmlInputHidden) FindControl(planRiskName);
string val = hiddenControl.Value;
}
}
This is one way to get the value from the request...
string point1 = Request.Form["point1"];
In CreateChildControls you are explicitly setting the value of the hidden field(s). CreateChildControls runs each time during the page lifecycle (potentially multiple times), when you click submit, the page posts back and runs through the entire lifecycle again - including CreateChildControls - before running the click handler Update_PlanRisks.
The simplest way to avoid this problem is to check if you are in PostBack before setting the value of your hidden fields:
if(!IsPostBack)
{
hiddenField.Value = Convert.ToString(pr.Severity);
}