if condition in aspx markup tag - asp.net

How do I set the value of primaryKey attribute in a gridview aspx markup bases on condition?
<%
string val=string.Empty;
if(Id=1){
%>
val="red";
<% else { %>
val="blue";
<%} %>
<GridView runat="server" id="someid" PrimaryKey=val />

Your code have issues, you need to fix that.
Issue 1
if(Id=1){ Not correct , it should be if(Id==1){
Issue 2:
Propriety should not be PrimaryKey it should be DataKeyNames
Issue 3:
<GridView runat="server" id="someid" PrimaryKey=val />
It should be
<asp:GridView runat="server" id="someid" />
Instead of using a variable and using that for setting, you can do it like following.
<%
string val = string.Empty;
if (Id == 1)
{
someid.PrimaryKey = "red";
}
else
{
someid.PrimaryKey = "blue";
}
%>
<asp:GridView runat="server" id="someid" />

Related

Using c# in Web Forms to passing parameter to user control

From an aspx page, I am trying to display a user control for each item in a collection, but the C# seems to be ignored when tryign to set the UserControl parameter:
<%foreach (Fetus item in this.pregnancy.Fetus) {%>
//this returns a GUID:
"<%= item.Id.ToString() %>"
//this does not work, returns the characters between "" like < %= item.Id.ToString()%>:
<uc1:AntepartumCTGChart runat="server" ID="AntepartumCTGChart" FetusId="<%= item.Id.ToString()%>" />
<% } %>
I would expect this to work, what's wrong?
You have to use a data binding expression
<uc1:AntepartumCTGChart runat="server" ID="AntepartumCTGChart" FetusId='<%# item.Id.ToString()%>' />
But you have to call DataBind() in code behind for that to work.
You can also use a Repeater
<asp:Repeater ID="Repeater1" runat="server">
<ItemTemplate>
<uc1:AntepartumCTGChart runat="server" ID="AntepartumCTGChart" FetusId='<%# Eval("id").ToString()%>' />
</ItemTemplate>
</asp:Repeater>
And then bind data to it in code behind
Repeater1.DataSource = pregnancy.Fetus;
Repeater1.DataBind();

Master Page not working on ASP.NET Page

I'm having trouble with my ASP.NET Webform. All my pages are working perfectly with the master page, but for some reason my ProductItem page isn't accepting the master page.
Heres my code for ProductItem:
<%# Page Title="Home Page" Language="C#" MasterPageFile="~/Site.Master" AutoEventWireup="true" CodeBehind="ProductItem.aspx.cs" Inherits="mumsBoutique.ProductItem" %>
<asp:Content ID="BodyContent" ContentPlaceHolderID="MainContent" runat="server">
<link href="Content/websiteStyle.css" rel="stylesheet" type="text/css" />
<h1><center>Product Details</center></h1>
<div class="row">
<asp:Label ID="productNameLabel" runat="server" Text="Product"></asp:Label>
<br />
<asp:Label ID="productItemNumber" runat="server" Text="ProductCode" CssClass="ProductItem_productNumber"></asp:Label>
</h3>
<h3>
<asp:Label ID="productCost" runat="server" Text="£0.00"></asp:Label>
</h3>
<p>
<asp:Image ID="productImage" runat="server" />
</p>
<h4>Product summary</h4>
<p>
<asp:Label ID="productDescription" runat="server" Text=""></asp:Label>
</p>
<!-- The right colum displays a text box for user to add items to the basket -->
<h3>Buy Item</h3>
<p>
<asp:ValidationSummary ID="ValidationSummary1" runat="server" CssClass="text-danger" />
<p>
Quantity: <asp:TextBox ID="itemQuantity" runat="server" Text="1"></asp:TextBox>
<asp:RequiredFieldValidator ID="rfvItemQuantity" runat="server" ErrorMessage="Quantity is required" Text="Please specify the quantity required" ControlToValidate="itemQuantity" CssClass="text-danger" Display="Dynamic"></asp:RequiredFieldValidator>
<asp:CompareValidator ID="cvItemQuantity" runat="server" ErrorMessage="Invalid quantity value" Text="Please specify a valid numeric quantity value" ControlToValidate="itemQuantity" Type="Integer" Display="Dynamic" CssClass="text-danger" Operator="DataTypeCheck"></asp:CompareValidator>
<asp:RangeValidator ID="rvItemQuantity" runat="server" ErrorMessage="Invalid quantity value" Text="Please specify a quantity value between 1 and 10" ControlToValidate="itemQuantity" Type="Integer" MinimumValue="1" MaximumValue="10" Display="Dynamic" CssClass="text-danger"></asp:RangeValidator>
</p>
<p>
<asp:Button ID="btnAddToBasket" runat="server" Text="Add to basket" CssClass="btn btn-primary btn-lg" OnClick="btnAddToBasket_Click" />
</p>
</div>
</asp:Content>
But I don't think the problem is on this particular page. It seems the problem occurs when I run the page from the hyperlink on the Bags.aspx page
<%# Page Title="Home Page" Language="C#" MasterPageFile="~/Site.Master" AutoEventWireup="true" CodeBehind="Bags.aspx.cs" Inherits="mumsBoutique.Bags" %>
<asp:Content ID="BodyContent" ContentPlaceHolderID="MainContent" runat="server">
<link href="Content/mumsBoutique.css" rel="stylesheet" type="text/css" />
<h1><center>Bags</center></h1>
<div class="row">
<asp:DataList ID="DataList1" runat="server" CssClass="table ProductsDataList" DataKeyField="productID" DataSourceID="SqlDataSource1" RepeatColumns="4" RepeatDirection="Horizontal">
<ItemTemplate>
<asp:Image ID="Image1" runat="server" Height="200px" Width="180px" ImageUrl='<%# Eval("Picture", "~/{0}") %>' />
<br />
<asp:HyperLink ID="HyperLink1" runat="server" NavigateUrl='<%# Eval("productID", "ProductItem.aspx/{0}") %>' Text='<%# Eval ("productName") %>'></asp:HyperLink>
<br />
Item Number:
<asp:Label ID="ItemNumberLabel" runat="server" Text='<%# Eval("productNumber") %>' />
<br />
<asp:Label ID="CostLabel" runat="server" Text='<%# Eval("cost", "{0:C}") %>' />
<br />
<br />
<br />
</ItemTemplate>
</asp:DataList>
<asp:SqlDataSource ID="SqlDataSource1" runat="server" ConnectionString="<%$ ConnectionStrings:DefaultConnection %>" SelectCommand="SELECT Items.productID, Items.productName, Items.productNumber, Items.picture, Items.cost, Items.categoryID, ItemCategories.Name AS Expr1 FROM ItemCategories INNER JOIN Items ON ItemCategories.categoryID = Items.categoryID WHERE (Items.categoryID = 2)"></asp:SqlDataSource>
</div>
</asp:Content>
Would really appreciate any help, been stuck for hours!
Update: Here are some screen shots of the problem I mean.
This is the Bags.aspx Page When you click on the hyperlink it takes you to the following
ProductItem.aspxAs can be seen the master page isn't being used for some reason. Yet in all other pages it works perfectly fine.
Here is the ProductItem.aspx.cs:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Microsoft.AspNet.FriendlyUrls;
using mumsBoutique.Models;
namespace mumsBoutique
{
public partial class ProductItem : System.Web.UI.Page
{
int _productID = 0;
protected void Page_Load(object sender, EventArgs e)
{
IList<string> segments = Request.GetFriendlyUrlSegments();
if (segments != null && segments.Count > 0)
{
// Convert the item ID to an integer and store it in the field _itemID
int.TryParse(segments[0], out _productID);
}
// If no item ID is specified, go back to the products page
if (_productID == 0)
{
Response.Redirect("Products");
}
// If _itemID is a valid value, search the database for the matching item
if (!IsPostBack && _productID > 0)
{
// open the connection to the database
using (ApplicationDbContext context = new ApplicationDbContext())
{
string sql = "SELECT * FROM Items WHERE productId = #productId";
System.Data.SqlClient.SqlParameter parameter = new System.Data.SqlClient.SqlParameter("#productId", _productID);
Item foundItem = context.Database.SqlQuery<Item>(sql, parameter).FirstOrDefault();
productNameLabel.Text = foundItem.productName;
productItemNumber.Text = foundItem.productNumber;
productCost.Text = foundItem.cost.ToString("c");
productImage.ImageUrl = "~/" + foundItem.picture;
productDescription.Text = foundItem.productDecription;
}
}
}
protected void btnAddToBasket_Click(object sender, EventArgs e)
{
// Check if page is valid
if (Page.IsValid)
{
int qty = 0;
// Get the quantity from the input field
qty = int.Parse(itemQuantity.Text);
// Check if item already exist in basket
OrderItem basketItem = ShopApp.Instance.GetBasketItem(_productID);
if (basketItem == null)
{
// item does not currently exist in basket, add new one
using (ApplicationDbContext context = new ApplicationDbContext())
{
// find the product item (pItem) with ItemId matching what is stored in the variable field (_itemId)
Item productItem = context.Items.FirstOrDefault(i => i.productID == _productID);
basketItem = new OrderItem()
{
productId = _productID,
Quantity = qty,
Price = double.Parse(productCost.Text, System.Globalization.NumberStyles.Currency),
Item = productItem
};
ShopApp.Instance.BasketItems.Add(basketItem);
}
}
else
{
// item already exists in basket, increase the quantity
basketItem.Quantity += qty;
}
((SiteMaster)Master).UpdateBasket();
}
}
}
}
It looks like you are trying to pass the productID as a parameter, so try changing NavigateUrl='<%# Eval("productID", "ProductItem.aspx/{0}") %>'
to
NavigateUrl='<%# Eval("productID", "ProductItem.aspx?productID={0}") %>'
Also, you need to move your CSS links to the appropriate place in your master page - you should not be linking to CSS style sheets from within a page when using a master page, and certainly not from within a ContentPlaceHolder section as you are not overriding any styles. This is more than likely the cause of your problem.
UPDATE
I've taken a look at your project and found the following problems, just by eyeballing it (can't run it due to diff DB version, etc):
The markup in your master page is badly formed. You are basically doing everything in the head section because you have no body section.
The link to your style sheet in the master page is outside of the
HTML document - it should be within the head section. Here is how structure of your master page should look:
<%# Master Language="C#" AutoEventWireup="true"
CodeBehind="Site.master.cs" Inherits="mumsBoutique.SiteMaster" %>
<!DOCTYPE html>
<html lang="en">
<head runat="server">
<meta charset="utf-8" />
<link href="Content/websiteStyle.css" rel="stylesheet"
type="text/css" />
</head>
<body>
<form id="form1" runat="server">
...
</form>
</body>
Remove the superfluous CSS links from your Bags and ProductItem
pages - when you have fixed the CSS link in the master page, that is
all you should need; you're obviously not overriding anything as you are specifying the same style sheet throughout.

ASP.NET Linkbutton not getting dynamic value for commandargument value

<%
foreach (training t in traininglist)
{
%>
<tr>
<td><%=t.TrainingId%></td>
<td><%=t.TrainingName%></td>
<td>
<asp:LinkButton runat="server" ID="EditBtn"
Text="Edit" OnCommand="editbtn_OnCommand"
CommandArgument='<%# t.TrainingId %>' CommandName="edit" />
</td>
</tr>
<% } %>
where,
training is the class and traininglist is List<training> defined in Page_Load() function in codebehind.
I am trying to call the
public void editbtn_OnCommand(object sender, CommandEventArgs e)
{
String myeid = e.CommandArgument.ToString();
....
}
Here, myeid is not getting value but always shows <%# t.TrainingId %>
i have already tried all other options like <%: t.TrainingId %> or <%=t.TrainingId %>
The output of Tag "<%= %>" is more likely similar to use Response.Write in your code. so these tags are used to display the value to the response object.
That's why,as per my understanding, You can't used these tags to set commandargument property of controls unless you are using DataBinding. If you are using DataBinding then these tags "<%= %>" are used to set the property of controls.
Because you are here looping through each item in list on html table, my suggestion is to use GridView or Repeater and then Bind through your List Object. if you are using this way, you can get rid of unwanted formatting issues of html tables also.
Refer http://msdn.microsoft.com/en-us/library/6dwsdcf5(VS.71).aspx
If you want to use repeater then you can use these specific tags, and this should be your code(not actual code, just sample one)
<asp:Repeater id="myRepeater" runat="server" >
<ItemTemplate>
<div>
<asp:LinkButton runat="server" id="EditBtn" CommandName="edit"
CommandArgument="<%#Container.DataItem.TrainingId %>" Text="Edit"
OnCommand="editbtn_OnCommand" />
</div>
</ItemTemplate>
</asp:Repeater>

error: "Object reference not set to an instance of an object."

I am new to C# and I am having a hard time solving an error. When I log in, I get the error:
Object reference not set to an instance of an object.".
I know this means the table does not exist, but how do I correct it? My Database contains 4 tables and the table I am referring to is the third table in the database(I don't know if this will help). Please tell me if you need more information. I think the problem is with the loop somewhere, because I get no syntax errors.
My login code in my web user control(just for background information)
<%# Control Language="C#" AutoEventWireup="true" CodeFile="WebUserControl.ascx.cs" Inherits="WebUserControl" %>
<% if (Session["Patient"] == "Logged In")
{ %>
<asp:Button ID="Logout" runat="server" Text="Logout" onclick="Logout_Click" /> <br /><br />
<a>Continue to:</a> <asp:LinkButton ID="homepage" runat="server" PostBackUrl="~/home.aspx">Home page</asp:LinkButton>|
<asp:LinkButton ID="book_appointment" runat="server" PostBackUrl="~/appointments.aspx">Book an Appointment</asp:LinkButton>
<asp:HyperLink ID="HyperLink1" runat="server" Visible="false">HyperLink</asp:HyperLink>
<% }
else
{ %>
<br />
<a>Username:
<asp:TextBox ID="username" runat="server"></asp:TextBox> <br /><br />
Password:
<asp:TextBox ID="password" runat="server" TextMode="Password"></asp:TextBox> </a><br /><br />
<asp:Button ID="Login" runat="server" Text="Login" onclick="Login_Click" />
<asp:LinkButton ID="linkRegister" runat="server" PostBackUrl="~/register.aspx">Register</asp:LinkButton><br /><br />
<a><asp:Literal ID="literal1" runat="server"></asp:Literal></a><br /><br />
<% } %>
This is the code behind on my login control:
protected void Login_Click(object sender, EventArgs e)
{
cQuery record = new cQuery(); //declare instance
record.Sqlstring = "SELECT username, password FROM dbo.patient_details"; //what to get from database -- sql query
DataSet data = record.SelectStatement(); //put info into dataset
DataTable table = data.Tables[0];
foreach (DataRow row in table.Rows)
{
if (row[0].ToString() == username.Text)
{
if (row[1].ToString() == password.Text)
{
Session["Patient"] = row[0];
Response.Redirect("myaccount.aspx");
return;
}
}
} }
I know this means the table does not exist
No, it doesn't. if the table did not exist yo would get a SQL error.
What it means (assuming it's occurring in the method you posted, which you haven't confirmed) is that one of the variables below is null:
row[0]
row[1]
username
password
Which I doubt unless you have a record with a null password, or the username and password controls are created dynamically. Look at the stack trace of the exception and you should be able to pinpoint where the error occurs.

Why is the content inside the invisible asp:PlaceHolder rendered?

Why is the content inside the placeholder rendered?
This code results in: "Object reference not set to an instance of an object."
For the MainGuard object!
How should one handle this situation?
<asp:PlaceHolder runat="server" Visible="<%# Model.MainGuard != null %>">
<asp:Image runat="server" ImageUrl="<%# Model.MainGuard.Image.RenderImage() %>" Height="50" />
<%# Model.MainGuard.Name %>
</asp:PlaceHolder>
It's not rendered -- but it still has to be parsed by the runtime, hence you still get the exception. Your only recourse is to check for null each time:
<asp:Image runat="server"
ImageUrl="<%# Model.MainGuard == null ? "" : Model.MainGuard.Image.RenderImage() %>" />
<%# Model.MainGuard == null ? "" : Model.MainGuard.Name %>
You might consider using an extension method to allow for cleaner syntax:
public static string StringOrEmpty(this MyClass self, Func<MyClass, string> selector)
{
if (self == null) return "";
return selector(self);
}
Then you can write:
<asp:Image runat="server"
ImageUrl="<%# Model.MainGuard.StringOrEmpty(mainGuard => mainGuard.Image.RenderImage()) %>" />
<%# Model.MainGuard.StringOrEmpty(mainGuard => mainGuard.Name) %>

Resources