I'm using ASP.NET Repeater for dynamically generating HTML code and pagination. I use totally same code on two aspx pages and on one all works fine, but on the other one I get an Exception: Object reference not set to an instance of an object.
Now I understand why the exception occurred, it simply has a null value, repeater didn't render I guess. But does anyone know why this error happened and how it's possible that it works on one page, and doesn't work on the other? Where should I look for "real" problem?
This is my HTML code on the aspx page:
<div class="accordion-wrap projects">
<asp:Repeater runat="server" ID="projectRepeter">
<ItemTemplate>
<div class="item">
<div class="heading">
<span>
<asp:Label runat="server" ID="TeamMemberName" Text='<%#Eval("ProjectName")%>'></asp:Label></span><span><em>x</em></span>
<i>+</i>
</div>
<div class="details">
<ul class="form">
<li>
<label>Project name:</label>
<input type="text" class="in-text" value="<%#Eval("ProjectName")%>" />
</li>
<li>
<label>Lead:</label>
<asp:DropDownList runat="server" DataSourceID="TeamMemberNameDS"></asp:DropDownList>
</li>
</ul>
<ul class="form">
<li>
<label>Description:</label>
<input type="text" class="in-text" value="<%#Eval("Description")%>" />
</li>
</ul>
<ul class="form last">
<li>
<label>Customer:</label>
<asp:DropDownList runat="server" DataSourceID="ClientNameDS"></asp:DropDownList>
</li>
<li class="inline">
<label>Status:</label>
<span class="radio">
<label for="inactive">Active:</label>
<input type="radio" value="1" name="status" id="inactive" />
</span>
<span class="radio">
<label for="active">Inactive:</label>
<input type="radio" value="2" name="status" id="active" />
</span>
<span class="radio">
<label for="active">Archive:</label>
<input type="radio" value="3" name="status" id="Radio1" />
</span>
</li>
</ul>
<div class="buttons">
<div class="inner">
Save
Delete
</div>
</div>
</div>
</div>
</ItemTemplate>
</asp:Repeater>
</div>
<div class="pagination">
<asp:Repeater ID="rptPagingProject" runat="server" OnItemCommand="rptPaging_ItemCommand">
<ItemTemplate>
<asp:LinkButton ID="btnPage"
CommandName="Page" CommandArgument="<%# Container.DataItem %>" runat="server" ForeColor="Black" Font-Bold="True"><%# Container.DataItem %>
</asp:LinkButton>
</ItemTemplate>
</asp:Repeater>
</div>
And this is the code behind:
protected void BindRepeater()
{
string ConnectionString = "Data Source=PRACTICE-001;Initial Catalog=n.mosorinski;User ID=n.mosorinski;Password=n.mosorinski;MultipleActiveResultSets=True;Application Name=EntityFramework";
SqlConnection con = new SqlConnection(ConnectionString);
SqlCommand cmd = new SqlCommand("SELECT p.ProjectName, p.Description, c.ClientName FROM Project AS p INNER JOIN Client AS c ON p.CustomerID = c.ClientID", con);
if (con.State == ConnectionState.Closed)
{
con.Open();
}
DataTable dt = new DataTable();
SqlDataAdapter adp = new SqlDataAdapter(cmd);
adp.Fill(dt);
PagedDataSource pgitems = new PagedDataSource();
DataView dv = new DataView(dt);
pgitems.DataSource = dv;
pgitems.AllowPaging = true;
pgitems.PageSize = 5;
pgitems.CurrentPageIndex = PageNumber;
if (pgitems.PageCount > 1)
{
rptPagingProject.Visible = true;
ArrayList pages = new ArrayList();
for (int i = 0; i < pgitems.PageCount; i++)
pages.Add((i + 1).ToString());
rptPagingProject.DataSource = pages;
rptPagingProject.DataBind();
}
else
{
rptPagingProject.Visible = false;
}
projectRepeter.DataSource = pgitems;
projectRepeter.DataBind();
}
public int PageNumber
{
get
{
if (ViewState["PageNumber"] != null)
return Convert.ToInt32(ViewState["PageNumber"]);
else
return 0;
}
set
{
ViewState["PageNumber"] = value;
}
}
protected void rptPaging_ItemCommand(object source, RepeaterCommandEventArgs e)
{
PageNumber = Convert.ToInt32(e.CommandArgument) - 1;
BindRepeater();
}
}
Related
I wanted to display 10 recent news from database. I have used LIMIT 10 in sql query to display 10 recent news. I am using bootstrap.
I am getting only 1 news from the database. I know that here I have to use datalist or listview in design. But I don't know how to implement it using Bootstrap.
Default.aspx:
<div class="container">
<h1 class="main-module-title">Recent <span>News</span></h1>
<%-- <asp:datalist runat="server">
<ItemTemplate>--%>
<div class="row-fluid">
<div class="row">
<div class="col-xs-12 col-sm-3 col-md-3">
<a href="#">
<asp:Image runat="server" ID="ImgNews" class="img-responsive img-box img-thumbnail"/>
</a>
</div>
<div class="col-xs-12 col-sm-9 col-md-9">
<h4><asp:Label ID="newsheader" runat="server" Text=""></asp:Label></h4>
<p runat="server" style="text-align:justify" id="newscontent"> </p>
</div>
</div>
<hr/>
</div>
<%-- </ItemTemplate>
</asp:datalist>--%>
</div>
Default.aspx.cs:
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
MySqlConnection conn = null;
string newsitem = null;
if (!(Request.QueryString["newstitle"] == null))
{
Page.Header.Title = Request.QueryString["newstitle"] + " - DubaiExporters ";
}
else
{
Page.Header.Title = "DubaiExporters - Dubai Business News - UAE Exports";
}
try
{
string connStr = ConfigurationManager.ConnectionStrings["mysqldbeConnectionString"].ToString();
string newssql = null;
newssql = "SELECT * FROM news WHERE status = b'1' AND linkstatus = b'1' ORDER BY datepublished DESC LIMIT 10";
conn = new MySqlConnection(connStr);
MySqlCommand cmd = new MySqlCommand(newssql, conn);
conn.Open();
MySqlDataReader r = cmd.ExecuteReader(CommandBehavior.CloseConnection);
if(r.Read())//while(r.Read())
{
newsheader.Text = HttpUtility.HtmlDecode(r["newstitle"].ToString().Trim()).ToString();
newscontent.InnerHtml = HttpUtility.HtmlDecode(r["newsbrief"].ToString().Trim()).ToString();
ImgNews.ImageUrl = "~/images/newspictures/" + r["image"].ToString();
}
}
catch (MySqlException ex)
{
}
catch (Exception ex)
{
}
finally
{
if (conn != null)
{
conn.Close();
}
}
}
}
try the below template and bind the DataList to DataSource in the Page Load event inside !Page.IsPOstBack condition
<asp:DataList ID="DataList1" runat="server">
<ItemTemplate>
<div class="row-fluid">
<div class="row">
<div class="col-xs-12 col-sm-3 col-md-3">
<a href="#">
<asp:Image runat="server" ID="ImgNews" class="img-responsive img-box img-thumbnail" ImageUrl='<%# "~/images/newspictures/" + Eval("image")%>' />
</a>
</div>
<div class="col-xs-12 col-sm-9 col-md-9">
<h4><a href="#">
<asp:Label ID="newsheader" runat="server" Text='<%# Eval("newstitle") %>'></asp:Label></a></h4>
<p runat="server" style="text-align: justify" id="newscontent"><%# Eval("newsbrief") %></p>
</div>
</div>
<hr />
</div>
</ItemTemplate>
</asp:DataList>
I am using Bootstrap carousel slider script inside Repeater but its not working proper.The data display at once and stack horizontal ,When I click NEXT or PREVIOUS in the carousel control, the carousel displays correctly but with only one item in every carousel i want to display 3 items in each carousel .
<!-- Begin Carousel -->
<div class="row">
<div id="realto-carousel-afee" class="carousel slide">
<div class="carousel-navigation pull-right"> <a class="serif italic pull-left view-all-carousel" href="properties-grid-layout-2">عرض الكل</a> <a class="left carousel-control pull-left" href="#realto-carousel-afee" data-slide="prev"><i class="fa fa-angle-left"></i></a> <a class="right carousel-control pull-right" href="#realto-carousel-afee" data-slide="next"><i class="fa fa-angle-right"></i></a> </div>
<div class="carousel-inner">
<asp:Repeater runat="server" ID="ProjectsRepater">
<ItemTemplate>
<div <%# Container.ItemIndex == 0 ? "active" : "" %>>
<div class="col-lg-4 col-md-4 col-sm-4 col-sx-12">
<div class="box-container">
<div class="holder"> <a class="overlay" href="" title=""> <span class="more"> <i class="fa fa-zoom-in"></i> </span>
<div class="prop_img"> <img width="370" height="210" src="150w" sizes="(max-width: 370px) 100vw, 370px" /> </div>
</a> <span class="prop-tag">للبيع</span>
<div class="prop-info">
<h3 class="prop-title">
<asp:Label ID="ProjId" runat="server" Visible="false" Text='<%# Eval("ID")%>'></asp:Label>
<asp:Label Text='<%# Eval("ProjectName")%>' ID="lblProjName" runat="server">مشروع 94 حي اللوتس الشمالية 2</asp:Label>
</h3>
<ul class="more-info clearfix">
<li class="info-label clearfix"> <span class="pull-left" style="float:right !important">المساحات</span>
<label id="lblArea" runat="server" class="qty pull-right">2</label>
</li>
<li class="info-label clearfix"> <span class="pull-left" style="float:right !important">نظام السداد</span> <span id="lblPaymentsSystem" runat="server" class="qty pull-right">2</span> </li>
<li class="info-label clearfix"> <span class="pull-left" style="float:right !important">تاريخ الاستلام</span> <span id="lblReceivedDate" runat="server" class="qty pull-right">2</span> </li>
</ul>
</div>
<!-- prop-info -->
</div>
<!-- holder -->
</div>
<!-- box-container -->
</div>
</div>
</ItemTemplate>
</asp:Repeater>
<!-- .carousel-inner -->
</div>
</div>
<!--End Carousel-->
</div>
in this code i select all projects and display them in repeater control by carousel slider
protected void Page_Load(object sender, EventArgs e)
{
// RepeterData();
ProjectsRepater.DataSource = GetAllProjecct();
ProjectsRepater.DataBind();
}
public class Proj
{
public int ID { get; set; }
public string ProjectName { get; set; }
}
public List<Proj> GetAllProjecct()
{
List<Proj> listproj = new List<Proj>();
SqlConnection con = new SqlConnection(System.Web.Configuration.WebConfigurationManager.ConnectionStrings["AlamarConnectionString"].ConnectionString);
SqlCommand com = new SqlCommand("Select ID,ProjectName from Projects", con);
con.Open();
SqlDataReader reader = com.ExecuteReader();
while (reader.Read())
{
Proj cnt = new Proj();
cnt.ID = Convert.ToInt32(reader["ID"]);
cnt.ProjectName = Convert.ToString(reader["ProjectName"]);
listproj.Add(cnt);
}
return listproj;
}
I have this code :
<div class="detailBox">
<div class="actionBox">
<ul class="commentList">
<%
foreach (System.Data.DataRow drow in members.Rows)
{
%>
<li>
<div class="commentText">
<span><%= drow["nume_user"] %></span>
<asp:Button ID="deleteButton" CssClass="btn btn-danger btn-xs" runat="server" OnClick="deleteMember" Text="Elimina" CommandArgument="<%= drow["id"] %>" />
</div>
</li>
<%
}
%>
</ul>
</div>
</div>
I don't know why I get this error Server tags cannot contain <% ... %> constructs. when I want to give CommandArgument the value of drow["id"], how can I pass this variable to the code behind when I click on the button ?
EDIT
And the code behind that's being executed when I click the button:
protected void deleteMember(object sender, EventArgs e)
{
String connString = System.Configuration.ConfigurationManager.ConnectionStrings["GroupsConnString"].ToString();
var argument = ((Button)sender).CommandArgument;
Response.Write(argument);
if (argument != null)
{
MySqlConnection conn = new MySqlConnection(connString);
conn.Open();
MySqlCommand comm = conn.CreateCommand();
comm.CommandText = "DELETE FROM app_groups.users_groups_leg WHERE id = " + argument;
int result = comm.ExecuteNonQuery(); //here you will get the no.of rows effected
conn.Close();
}
}
I think you should use <%# %> to switch between c# and html. So your code should be
<div class="detailBox">
<div class="actionBox">
<ul class="commentList">
<%#
foreach (System.Data.DataRow drow in members.Rows)
{
%>
<li>
<div class="commentText">
<span><%= drow["nume_user"] %></span>
<asp:Button ID="deleteButton" CssClass="btn btn-danger btn-xs" runat="server" OnClick="deleteMember" Text="Elimina" CommandArgument="<%= drow["id"] %>" />
</div>
</li>
<%#
}
%>
</ul>
</div>
</div>
I'm working on a project and ran into a problem.
For some reason, I can't assign data source to the repeater. I'm using usercontrol
SlideshowDemo.ascx
<asp:Repeater ID="Slideshow" runat="server">
<HeaderTemplate>
<div style="margin:0 auto; width:960px;">
<div class="slideshowInsideContainer">
<div class="slideShowText">
<div style="padding:10px;" class="SlideShowContent">
<%= firstText %>
</div>
</div>
<img id="SlideShowImage" style="position:absolute; z-index:1; top:0;" src="<%= firstImage %>" />
<img id="SlideShowImageBG" style="position:absolute; z-index:0; top:0;" src="<%= firstImage %>" />
<img id="previousBttn" style="position:absolute; z-index:2; top:200px; cursor:pointer; left:0;" src="/images/SlideShow/leftButton.png" />
<img id="nextBttn" style="position:absolute; z-index:2; top:200px; cursor:pointer; right:0;" src="/images/SlideShow/rightButton.png" />
<div class="slideshowItems">
<ul>
</HeaderTemplate>
<ItemTemplate>
<li class='<%# Container.ItemIndex == 0 ? "selected" : "" %>' id="<%# Container.ItemIndex %>">
<div class="slideshowtext">
<%# Eval("text") %>
</div>
<img style="position:absolute; z-index:1; top:0;" src=' <%# Eval("image") %>' />
</li>
</ItemTemplate>
<FooterTemplate>
</ul>
</div>
</div>
</div>
</FooterTemplate>
</asp:Repeater>
SlideshowDemo.ascx.cs
public void GetSlideshowData()
{
int ID = Convert.ToInt32(slideShowID);
Node parent = new Node(ID);
ArrayList repeaterData = new ArrayList();
Nodes children = parent.Children;
for (int i = 0; i < children.Count; i++)
{
string image = children[i].GetProperty("image").Value.ToString();
string text = children[i].GetProperty("slideshowText").Value.ToString();
if (i == 0)
{
firstImage = image;
firstText = text;
}
repeaterData.Add(new SlideShowItem(image, text));
}
Slideshow.DataSource = repeaterData; //Error: Can't recognize 'Slideshow'
Slideshow.DataBind();
}
The problem is that the SlideshowDemo.ascx.cs doesn't recognize Slideshow
I get error
The name 'Slideshow' does not exist in the current context
I also get Warning
Source file
'obj\Debug\TemporaryGeneratedFile_E7A71F73-0F8D-4B9B-B56E-8E70B10BC5D3.cs'
specified multiple times
I would appreciate any help
I have to use multiple bootstrap carousel in single page, using the asp repeater control but it doesn't work, it just show one slider on the page
Here is the html and asp code
<div class="col-md-12">
<div id="Carousel" class="carousel slide">
<!-- Carousel items -->
<div class="carousel-inner">
<div class="item">
<div class="row">
<asp:Repeater runat="server" ID="Slider1">
<ItemTemplate>
<div class="col-md-2">
<div class="row">
<a target="_blank" href="<%# Eval("URL") %>">
<img class="caption" src="../Includes/gaceta/<%# Eval("Titulo") %>/files/res/pages/page_0000.jpg" alt="<%# Eval("Titulo") %>" width="188" height="222" /></a>
</div>
</div>
</ItemTemplate>
</asp:Repeater>
</div>
<!--.row-->
</div>
</div>
<!--.carousel-inner-->
<a data-slide="prev" href="#Carousel" class="left carousel-control">‹</a>
<a data-slide="next" href="#Carousel" class="right carousel-control">›</a>
</div>
<!--.Carousel-->
</div>
<hr />
<div class="col-md-12">
<div id="Carousel2" class="carousel slide">
<!-- Carousel items -->
<div class="carousel-inner">
<div class="item">
<div class="row">
<asp:Repeater runat="server" ID="Slider2">
<ItemTemplate>
<div class="col-md-2">
<div class="row">
<a target="_blank" href="<%# Eval("URL") %>">
<img class="caption" src="../Includes/gaceta/<%# Eval("Titulo") %>/files/res/pages/page_0000.jpg" alt="<%# Eval("Titulo") %>" width="188" height="222" /></a>
</div>
</div>
</ItemTemplate>
</asp:Repeater>
</div>
<!--.row-->
</div>
</div>
<!--.carousel-inner-->
<a data-slide="prev" href="#Folletos" class="left carousel-control">‹</a>
<a data-slide="next" href="#Folletos" class="right carousel-control">›</a>
</div>
<!--.Carousel-->
the javascript
$(document).ready(function () {
$('#Carousel').carousel('pause');
$('#Carousel2').carousel('pause');
$("div.item:first").addClass("active");
});
and the methods to bind the repeater
protected void Page_Load(object sender, EventArgs e)
{
BindSlider1(5);
BindSlider2(1);
}
protected void BindSlider1(int Ubicacion)
{
using (SqlConnection con = Conexion.Conecta())
{
using (SqlCommand cmd = new SqlCommand("SelGacetaUbicacion", con))
{
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Add("#UBICACION", SqlDbType.Int).Value = Ubicacion;
con.Open();
Slider1.DataSource = cmd.ExecuteReader();
Slider1.DataBind();
}
}
}
protected void BindSlider2(int Ubicacion)
{
using (SqlConnection con = Conexion.Conecta())
{
using (SqlCommand cmd = new SqlCommand("SelGacetaUbicacion", con))
{
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Add("#UBICACION", SqlDbType.Int).Value = Ubicacion;
con.Open();
Slider2.DataSource = cmd.ExecuteReader();
Slider2.DataBind();
}
}
}
I tried your code, and found this issues:
1- Review how to build the carousel markup depending on which version of bootstrap you are using. I tried with Bootstrap v3.1.0 and had to change parts of your markup. Refer to documentation or this sample.
For instance, <div class="item"> should be placed inside your repeater, and should have a <div class="container"> immediatly inside of it.
2- You are not initializing correctly both carousels from jquery, do something like this to correct it:
$("#Carousel div.item:first").addClass("active");
$("#Carousel2 div.item:first").addClass("active");