ASP.NET dataset add relation null reference exception - asp.net

I'm using this article as a guide to doing a nested data bind of my two tables 'Comment' 'CommentOtherAuthor': http://support.microsoft.com/kb/306154. There may be many authors to one comment. The code I have is here:
.ASPX:
<asp:Repeater ID="rptComments" runat="server">
<ItemTemplate>
<div class="comment-data">
<h3 class="item">Submitted to <%# GetPageDetails(Eval("nodeid")) %> article on <%# Eval("created") %></strong></h3>
<p class="item"><strong>Name</strong> <%# Eval("firstname") %> <%# Eval("surname") %></p>
<p class="item"><strong>Occupation</strong> <%# Eval("occupation") %></p>
<p class="item"><strong>Affiliation</strong> <%# Eval("affiliation") %></p>
<p class="item"><strong>Email</strong> <a href='mailto:<%# Eval("email") %>'><%# Eval("email") %></a> <em>Publish email: <%# Eval("publishemail") %></em></p>
<p class="item"><strong>Competing interests?</strong> <%# Eval("competingintereststext") %> </p>
<p class="item"><strong>eLetter title</strong> <%# Eval("title") %></p>
<p><%# Eval("comment").ToString().Replace("\n", "<br/>")%></p>
<div class="additional-authors">
<h3>Additional authors</h3>
<asp:Repeater id="rptAdditionalAuthors" runat="server" datasource='<%# ((DataRowView)Container.DataItem).Row.GetChildRows("myrelation") %>' >
<ItemTemplate>
<%# DataBinder.Eval(Container.DataItem, "[\"firstname\"]")%><br>
</ItemTemplate>
</asp:Repeater>
</div>
</div>
</ItemTemplate>
</asp:Repeater>
Codebehind:
private void BindData()
{
SqlConnection cnn = new SqlConnection(GlobalSettings.DbDSN);
SqlDataAdapter cmd1 = new SqlDataAdapter(string.Format("select * from Comment {0} order by created desc", Filter), cnn);
//Create and fill the DataSet.
DataSet ds = new DataSet();
cmd1.Fill(ds, "comments");
//Create a second DataAdapter for the additional authors table.
SqlDataAdapter cmd2 = new SqlDataAdapter("select * from CommentOtherAuthor", cnn);
cmd2.Fill(ds, "additionalAuthors");
//Create the relation between the comments and additional authors tables.
ds.Relations.Add(
"myrelation",
ds.Tables["Comment"].Columns["id"],
ds.Tables["CommentOtherAuthor"].Columns["commentid"]
);
//Bind the Authors table to the parent Repeater control, and call DataBind.
rptComments.DataSource = ds.Tables["additionalAuthors"];
rptComments.DataBind();
}
However, when running this it throws a System.NullReferenceException on the line ds.Relations.Add(
I'm really not sure where to start in fixing this as I'm way out of my depth here.
Can anyone advise how to get this working?
Thanks.

Got it! There was no actual foreign key constraint joining the tables. With that in place this now works.

Related

Save texbox text to SQL Server in ASP.NET website

I have a website in ASP.NET and I have a textbox that the user type in text. I want to save this into a SQL Server database that saves all other data from site. I have tried several ways and got to the code below. It throws up the error below
Any help as I'm lost on this now....
Error:
The name 'txtName' does not exist in the current context Step9.aspx.cs 67
Page markup:
<%# Page Title="" Language="C#" MasterPageFile="~/MasterPage.master" AutoEventWireup="true" CodeFile="Step9.aspx.cs" Inherits="Step1" %>
<asp:Content ID="Content1" ContentPlaceHolderID="head" Runat="Server">
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="ContentPlaceHolder1" Runat="Server">
<div class="question" id="question">
<table border="1" style="border-collapse: collapse">
<tr>
<td style="width: 150px">
Name:<br />
<asp:TextBox ID="txtName" runat="server" Width="140" />
</td>
<td style="width: 100px">
<asp:Button ID="btnAdd" runat="server" Text="Add" OnClick="Insert" />
</td>
</tr>
</table>
</div>
</asp:Content>
C# codebehind:
protected void Insert(object sender, EventArgs e)
{
string name = txtName.Text;
string constr = ConfigurationManager.ConnectionStrings["constr"].ConnectionString;
using (SqlConnection con = new SqlConnection(constr))
{
using (SqlCommand cmd = new SqlCommand("INSERT INTO learners (stickTwistBefore) VALUES (#stickTwistBefore)"))
{
using (SqlDataAdapter sda = new SqlDataAdapter())
{
cmd.Parameters.AddWithValue("#stickTwistBefore", name);
cmd.Connection = con;
con.Open();
cmd.ExecuteNonQuery();
con.Close();
}
}
}
// this.BindGrid();
}
I noticed that you have specified Step1 class name as Inherits attribute. Ensure that it matches the class name in your Step9.aspx.cs file. I guess Step9 but just confirm.
<%# Page Title="" Language="C#" MasterPageFile="~/MasterPage.master" AutoEventWireup="true" CodeFile="Step9.aspx.cs" Inherits="Step1" %>

losing the first result of retrieved data when binding it to repeater control

I am developing a social network in which i must show a list of friends to the current user.
i am using SqlDataReader to retrieve data from database then bind it by a repeater , the problem is that the repeater always skip the first result so it only shows the n-1 results out of n. anybody can explain to me this behaviour?
my code is:
string cmdstr2 = "SELECT students.fname, students.lname,students.username FROM students INNER JOIN friends ON students.username = friends.tostudent WHERE (friends.fromstudent ='" + cuser + "')";
SqlCommand cmd2 = new SqlCommand(cmdstr2, sc);
SqlDataReader rd = cmd2.ExecuteReader();
if (rd.Read())
{
Repeater1.DataSource = rd;
Repeater1.DataBind();
}
in the design view, i have written this code to include the repeater in the page:
<asp:Repeater ID="Repeater1" runat="server">
<HeaderTemplate>
<div style="font-size:xx-large;">
الأصدقاء</div>
</HeaderTemplate>
<ItemTemplate>
<div style="font-size:x-large; color:Black; margin-right:0px; margin-top:0px;">
<asp:HyperLink ID="HyperLink1" runat="server"
NavigateUrl='<%# "student.aspx?user="+DataBinder.Eval(Container.DataItem,"username")%>' >
<%#DataBinder.Eval(Container.DataItem, "fname")%> <%#DataBinder.Eval(Container.DataItem, "lname")%>
</asp:HyperLink>
</div>
</ItemTemplate>
<FooterTemplate>
</FooterTemplate>
</asp:Repeater>
Your rd.Read() in your if statement is advancing it 1 record
Try using:
if (rd.HasRows)

ASP display subcategories with similar categories using repeater

I'm trying to build a large menu with div's for each "Category". In each div the H3 is based on the "Category" that I'm pulling from a SQL table. Under the will be a with list items that are subCategories for each Category...which are links.
In the table there a bunch of Category items.
How can I loop through to show the Category and the subCategories associated with that category?
Here is how my html is set up:
<asp:Repeater id="dlCategories" runat="server" DataSourceID="LarryColeSub">
<ItemTemplate>
<div class="col_1">
<h3><%# Eval("Category") %></h3>
<ul>
<ItemTemplate>
<li><a id="cmdSubCategory" class="sectioncontentslink" href='default.aspx?rPage=ToolList&subCatID=<%# Eval("SubCategoryID")%>'>
<%# Eval("SubCategory") %></a></li>
</ItemTemplate>
</ul>
</div>
</ItemTemplate>
</asp:Repeater>
Here is my sqlDataSource:
<asp:SqlDataSource ConnectionString="<%$ ConnectionStrings:LarryCole %>" ID="LarryColeSub" runat="server" SelectCommand="SELECT [SubCategoryID],[SubCategory],[Category],[fkCategoryId] FROM [tblSubCategory]">
When I run this now it (obviously) creates a div for each subCategory vs a div for each Category.
<%# Control Language="c#" %>
<%# Import Namespace="System.Data" %>
<%# Import Namespace="System.Data.SqlClient" %>
<%# Import Namespace="System.Configuration" %>
<script runat="server">
protected void Page_Load(object sender, System.EventArgs e) {
if (!Page.IsPostBack) {
SqlConnection MyConnection;
SqlCommand MyCommand;
SqlDataAdapter MyAdapter;
DataTable MyTable;
DataSet ds;
ds = new DataSet();
MyConnection = new SqlConnection();
MyConnection.ConnectionString = ConfigurationManager.ConnectionStrings["db_name_here"].ConnectionString;
MyCommand = new SqlCommand();
MyCommand.CommandType = CommandType.Text;
MyCommand.Connection = MyConnection;
MyCommand.CommandText = "SELECT * FROM tblSubCategory";
MyTable = new DataTable();
MyAdapter = new SqlDataAdapter();
MyAdapter.SelectCommand = MyCommand;
MyAdapter.Fill(ds,"SubCategory");
MyCommand.Dispose();
MyCommand.CommandText = "SELECT * FROM tblCategory";
MyTable = new DataTable();
MyAdapter = new SqlDataAdapter();
MyAdapter.SelectCommand = MyCommand;
MyAdapter.Fill(ds,"Category");
MyCommand.Dispose();
ds.Relations.Add("myrelation",ds.Tables["Category"].Columns["CategoryID"], ds.Tables["SubCategory"].Columns["fkCategoryID"]);
//populate parent repeater
rpCategories.DataSource = ds.Tables["Category"];
rpCategories.DataBind();
MyAdapter.Dispose();
MyConnection.Dispose();
}
}
</script>
//html repeater code
<asp:Repeater id="rpCategories" runat="server">
<ItemTemplate>
<div class="col_1">
<h3><%# DataBinder.Eval(Container.DataItem,"Category") %></h3>
<ul>
<asp:Repeater id="rpSubCategories" runat="server" datasource='<%# ((DataRowView)Container.DataItem).Row.GetChildRows("myrelation") %>'>
<ItemTemplate>
<li><a id="cmdSubCategory" class="sectioncontentslink" href='default.aspx?varName=BlahBlah&subCatID=<%# ((DataRow)Container.DataItem)["SubCategoryID"] %>'>
<%# ((DataRow)Container.DataItem)["SubCategory"] %></a>
</li>
</ItemTemplate>
</asp:Repeater>
</ul>
</div>
</ItemTemplate>
</asp:Repeater

ASP.NET Repeater bind List<string>

I am binding a List<string> to a Repeater control. Now I want to use the Eval function
to display the contents in ItemTemplate like
<%# Eval("NAME") %>.
But I am not sure what I should use instead of NAME.
Just use <%# Container.DataItem.ToString() %>
If you are worried about null values you may want to refactor to this (.NET 6+)
<asp:Repeater ID="repeater" runat="server">
<ItemTemplate>
<%# Container.DataItem?.ToString() ?? string.Empty%>
</ItemTemplate>
</asp:Repeater>
Note if you are using less than .NET 6 you cannot use the null-conditional operator Container.DataItem?.ToString()
Set the ItemType to System.String
<asp:Repeater ItemType="System.String" runat="server">
<ItemTemplate>
<%# Item %>
</ItemTemplate>
</asp:Repeater>
rptSample.DataSource = from c in lstSample select new { NAME = c };
in the repeater you put
<%# Eval("NAME") %>
This should work just fine:
<ItemTemplate>
<%=this.GetDataItem().ToString() %>
</ItemTemplate>
A more complete example based on the LINQ provided by #RobertoBr:
In code behind:
List<string> notes = new List<string>();
notes.Add("Value1")
notes.Add("Value2")
repeaterControl1.DataSource = from c in notes select new {NAME = c};
repeaterControl1.DataBind();
On page:
<asp:Repeater ID="repeaterControl1" runat="server" >
<ItemTemplate>
<li><%# Eval("NAME") %></li>
</ItemTemplate>
</asp:Repeater>
you have to use the databind syntax here or it will not work.
<%# this.GetDataItem().ToString() %>
Inside Item Template
<ItemTemplate>
<asp:Label ID="lblName" runat="server" Text='<%# Eval("YourEntityName").ToString() ==""? "NA" : Eval("YourEntityName").ToString()%>'></asp:Label>
<ItemTemplate>
or Simply Add inside Item Template
<%# Eval("YourEntityName").ToString() ==""? "NA" : Eval("YourEntityName").ToString()%>

ASP.NET Datalist calculate field

I recently decided to implement tax on an ecommerce website I've built for fun more than anything and I've hit a stumbling block.
My implementation works well, tax is applied correctly etc, however a buddy pointed out to me today that prices on product pages are normally displayed inc tax.
I was thinking, rather than editing the Business and Data tier, I could change this on the DataList itself but I can't for the life of me work out how I'd actually do that. I've had a look in some text books and had a search around online but because I don't actually know what I'm looking for, I'm stuck :(.
Datalist:
<asp:DataList ID="list" runat="server" RepeatColumns="2" CssClass="ProductList" RepeatDirection="Horizontal"
Width="542px" EnableViewState="False" onitemcommand="list_ItemCommand">
<ItemTemplate>
<div style="width:271px;">
<h3 class="ProductName"><%# HttpUtility.HtmlEncode(Eval("Name").ToString()) %></h3>
<img width="100" border="0" src="<%# Link.ToProductImage(Eval("Thumbnail").ToString()) %>" alt='<%# HttpUtility.HtmlEncode(Eval("Name").ToString()) %>' />
<%# HttpUtility.HtmlEncode(Eval("Description").ToString()) %>
<p>
<b>Price:</b>
<%# Eval("Price", "{0:c}") %>
</p>
<p>
<asp:Button ID="addToCartButton" runat="server" Text="Add to Basket" CommandArgument='<%# Eval("ProductID") %>' CssClass="SmallButtonText" />
</p>
</div>
</ItemTemplate>
</asp:DataList>
Code behind:
// Retrieve the list of products in a Sub Category
list.DataSource = CatalogAccess.GetProductsInSubCategory(subCategoryId, page, out howManyPages);
list.DataBind();
E.g. if the price in the DB is £5, I'd need it to be displayed in the datalist above as £6 which includes the current UK VAT rate of 20%.
So:
DBPrice * 1.2 = IncVatPrice
I hope this makes sense!
Thanks in advance,
Matt
Instead of
<%# Eval("Price", "{0:c}") %>
use an expression somewhat similar to
<%# String.Format("{0:c}", (Decimal)Eval("Price")*1.2) %>
Or implement a function in codebehind:
protected string IncludeVat(object dataItem)
{
Decimal price = (Decimal)DataBinder.Eval(dataItem, "Price");
return String.Format("{0:c}", price * 1.2);
}
and call it in your DataList like that
<%# IncludeVat(Container.DataItem) %>
http://www.pluralsight-training.net/community/blogs/fritz/archive/2005/12/16/17507.aspx

Resources