I am making email client in asp.net C#. In it, GridView is not taking data of more than 5 rows. I am having 250 mails in my mailbox. But GridView is not showing that data. It is showing only up to 5 rows and after that five to six rows data are presented out of the GridView.
<%# Page Language="C#" AutoEventWireup="true" CodeFile="CS.aspx.cs" Inherits="CS" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js">
</script>
<script src="http://ajax.aspnetcdn.com/ajax/jquery.ui/1.8.9/jquery-ui.js" type="text/javascript">
</script>
<link href="http://ajax.aspnetcdn.com/ajax/jquery.ui/1.8.9/themes/start/jquery-ui.css"
rel="stylesheet" type="text/css"
/>
<script type="text/javascript">
$("[id*=lnkView]").live("click", function () {
var subject = $(this).text();
var row = $(this).closest("tr");
$("#body").html($(".body", row).html());
$("#attachments").html($(".Attachments", row).html());
$("#dialog").dialog({
title: subject,
buttons: {
Ok: function () {
$(this).dialog('close');
}
}
});
return false;
});
</script>
</head>
<body style="font-family: Arial; font-size: 10pt">
<form id="form1" runat="server">
<asp:GridView ID="gvEmails" runat="server" OnRowDataBound="OnRowDataBound" DataKeyNames="MessageNumber"
AutoGenerateColumns="false">
<Columns>
<asp:BoundField HeaderText="From" DataField="From" HtmlEncode="false" />
<asp:TemplateField HeaderText="Subject">
<ItemTemplate>
<asp:LinkButton ID="lnkView" runat="server" Text='<%# Eval("Subject") %>' />
<span class="body" style="display: none">
<%# Eval("Body") %></span>
</ItemTemplate>
</asp:TemplateField>
<asp:BoundField HeaderText="Date" DataField="DateSent" />
<asp:TemplateField ItemStyle-CssClass="Attachments">
<ItemTemplate>
<asp:Repeater ID="rptAttachments" runat="server">
<ItemTemplate>
<asp:LinkButton ID="lnkAttachment" runat="server" OnClick="Download" Text='<%# Eval("FileName") %>' />
</ItemTemplate>
<SeparatorTemplate>
<br>
</SeparatorTemplate>
</asp:Repeater>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
<div id="dialog" style="display: none">
<span id="body"></span>
<br />
<span id="attachments"></span>
</div>
</form>
</body>
</html>
Code Behind:
public partial class CS : System.Web.UI.Page
{
protected List<Email> Emails
{
get { return (List<Email>)ViewState["Emails"]; }
set { ViewState["Emails"] = value; }
}
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
this.Read_Emails();
}
}
private void Read_Emails()
{
Pop3Client pop3Client;
if (Session["Pop3Client"] == null)
{
pop3Client = new Pop3Client();
pop3Client.Connect("pop.gmail.com", 995, true);
pop3Client.Authenticate("example#gmail.com", "password", AuthenticationMethod.TryBoth);
Session["Pop3Client"] = pop3Client;
}
else
{
pop3Client = (Pop3Client)Session["Pop3Client"];
}
int count = pop3Client.GetMessageCount();
this.Emails = new List<Email>();
int counter = 0;
for (int i = count; i >= 1; i--)
{
Message message = pop3Client.GetMessage(i);
Email email = new Email()
{
MessageNumber = i,
Subject = message.Headers.Subject,
DateSent = message.Headers.DateSent,
From = string.Format("<a href = 'mailto:{1}'>{0}</a>", message.Headers.From.DisplayName, message.Headers.From.Address),
};
MessagePart body = message.FindFirstHtmlVersion();
if (body != null)
{
email.Body = body.GetBodyAsText();
}
else
{
body = message.FindFirstPlainTextVersion();
if (body != null)
{
email.Body = body.GetBodyAsText();
}
}
List<MessagePart> attachments = message.FindAllAttachments();
foreach (MessagePart attachment in attachments)
{
email.Attachments.Add(new Attachment
{
FileName = attachment.FileName,
ContentType = attachment.ContentType.MediaType,
Content = attachment.Body
});
}
this.Emails.Add(email);
counter++;
if (counter > count)
{
break;
}
gvEmails.DataSource = this.Emails;
gvEmails.DataBind();
}
//gvEmails.DataSource = this.Emails;
//gvEmails.DataBind();
}
protected void OnRowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
Repeater rptAttachments = (e.Row.FindControl("rptAttachments") as Repeater);
List<Attachment> attachments = this.Emails.Where(email => email.MessageNumber == Convert.ToInt32(gvEmails.DataKeys[e.Row.RowIndex].Value)).FirstOrDefault().Attachments;
rptAttachments.DataSource = attachments;
rptAttachments.DataBind();
}
}
protected void Download(object sender, EventArgs e)
{
LinkButton lnkAttachment = (sender as LinkButton);
GridViewRow row = (lnkAttachment.Parent.Parent.NamingContainer as GridViewRow);
List<Attachment> attachments = this.Emails.Where(email => email.MessageNumber == Convert.ToInt32(gvEmails.DataKeys[row.RowIndex].Value)).FirstOrDefault().Attachments;
Attachment attachment = attachments.Where(a => a.FileName == lnkAttachment.Text).FirstOrDefault();
Response.AddHeader("content-disposition", "attachment;filename=" + attachment.FileName);
Response.ContentType = attachment.ContentType;
Response.BinaryWrite(attachment.Content);
Response.End();
}
}
[Serializable]
public class Email
{
public Email()
{
this.Attachments = new List<Attachment>();
}
public int MessageNumber { get; set; }
public string From { get; set; }
public string Subject { get; set; }
public string Body { get; set; }
public DateTime DateSent { get; set; }
public List<Attachment> Attachments { get; set; }
}
[Serializable]
public class Attachment
{
public string FileName { get; set; }
public string ContentType { get; set; }
public byte[] Content { get; set; }
}
Related
I'm trying to use ASPxGridView to display a list of ASPxComboBox controls. Both the rows in the grid and the list of options in the combo boxes are populated from code. I'm having problems setting the initial value of the combo boxes.
I'm looking for it to look similar to the image below.
As you can see in the screenshot, I have been able to get both the grid view & the combo boxes to populate, but I can't figure out how to set the initial values of the combo boxes.
In the Init event of the inner combo boxes, there's no obvious property to retrieve the bound object.
I did find a couple other questions on StackOverflow, for which the answer was to add a bound property to the combo box. However, adding SelectedIndex='<%# Bind("Level") %>' to the declaration for InnerCombo gave me the error "Databinding methods such as Eval(), XPath(), and Bind() can only be used in the context of a databound control."
Here's what I have so far:
Testing.aspx:
<%# Page Title="" Language="C#" MasterPageFile="~/Light.master"
AutoEventWireup="true" CodeBehind="Testing.aspx.cs" Inherits="MyProject.Testing" %>
<asp:Content ID="Content1" ContentPlaceHolderID="MainContent" runat="server">
<dx:ASPxGridView ID="MyGridView" runat="server" KeyFieldName="Name">
<Columns>
<dx:GridViewDataColumn FieldName="Name" />
<dx:GridViewDataColumn FieldName="Level">
<DataItemTemplate>
<dx:ASPxComboBox
runat="server"
ID="InnerCombo"
ValueField="ID"
TextField="Desc"
ValueType="System.Int32"
OnInit="InnerCombo_Init" />
</DataItemTemplate>
</dx:GridViewDataColumn>
</Columns>
</dx:ASPxGridView>
<dx:ASPxButton runat="server" ID="btnSubmit" Text="Submit" OnClick="btnSubmit_Click" />
</asp:Content>
Testing.aspx.cs:
public partial class Testing : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!this.IsPostBack)
{
this.MyGridView.DataSource = GetDefaultSettings();
this.MyGridView.DataBind();
}
}
protected void btnSubmit_Click(object sender, EventArgs e)
{
Debug.WriteLine("btnSubmit_Click");
for (int i = 0; i < MyGridView.VisibleRowCount; i++)
{
object[] row = (object[])MyGridView.GetRowValues(i, "Name", "Value");
// row[1] is null, but we can get the data by finding the combo box itself.
GridViewDataColumn col = (GridViewDataColumn)MyGridView.Columns["Value"];
ASPxComboBox innerCombo = (ASPxComboBox)MyGridView.FindRowCellTemplateControl(i, col, "InnerCombo");
Debug.WriteLine("{0} = {1}", row[0], innerCombo.Value);
}
}
protected void InnerCombo_Init(object sender, EventArgs e)
{
Debug.WriteLine("InnerCombo_Init");
ASPxComboBox innerCombo = sender as ASPxComboBox;
if (innerCombo != null)
{
innerCombo.DataSource = GetValues();
innerCombo.DataBind();
}
}
private static List<ValueClass> GetValues()
{
// Simple for testing; actual method will be database access.
return new List<ValueClass>()
{
new ValueClass(0, "Zero (default)"),
new ValueClass(1, "One"),
new ValueClass(2, "Two"),
new ValueClass(3, "Three"),
};
}
private static List<SettingClass> GetDefaultSettings()
{
// Simple for testing; actual method will be database access + post-processing.
return new List<SettingClass>()
{
new SettingClass("AA", 0),
new SettingClass("BB", 1),
new SettingClass("CC", 0),
};
}
public class ValueClass
{
public int ID { get; private set; }
public string Desc { get; private set; }
public ValueClass(int id, string desc)
{
this.ID = id;
this.Desc = desc;
}
}
public class SettingClass
{
public string Name { get; set; }
public int Value { get; set; }
public SettingClass(string name, int value)
{
this.Name = name;
this.Value = value;
}
}
}
I have WebUserControl with DataBind override:
public partial class WebUserControl1 : System.Web.UI.UserControl
{
public object DataSource { get; set; }
public string Text { get; set; }
protected void Page_Load(object sender, EventArgs e)
{
}
public override void DataBind()
{
// *** there when called, properties are null, why? ***
repeater2.DataSource = DataSource;
repeater2.DataBind();
}
}
This control is in repeater with declarative bounded properties:
<asp:Repeater ID="repeater" runat="server">
<ItemTemplate>
<WebUserControl1 runat="server" DataSource='<%# DataBinder.Eval(Container.DataItem, "levels") %>' Text='<%# DataBinder.Eval(Container.DataItem, "Text") %>' />
</ItemTemplate>
</asp:Repeater>
Now when i call DataBind() on repeater:
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
... data query
repeater.DataSource = items;
repeater.DataBind();
}
}
in overriden control's DataBind() method i don't have properly setted properties DataSource and Text, they are null, why?
If you have only one repeater control in WebUserControl1, it is easier to bind that child repeater control in Repeater.ItemDataBound Event of Parent repeater.
Here is the sample -
ASPX
<asp:Repeater ID="ParentRepeater" runat="server" OnItemDataBound="ParentRepeater_ItemDataBound">
<ItemTemplate>
<asp:Label runat="server" ID="StreetLabel" /><br/>
<asp:Repeater ID="ChildRepeater" runat="server">
<ItemTemplate>
<asp:Label runat="server" ID="FirstNameLabel" />
<asp:Label runat="server" ID="LastNameLabel" />
</ItemTemplate>
</asp:Repeater><hr/>
</ItemTemplate>
</asp:Repeater>
Code Behind
public class Address
{
public int Id { get; set; }
public string Street { get; set; }
public List<User> Users { get; set; }
}
public class User
{
public int Id { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
}
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
ParentRepeater.DataSource = new List<Address>
{
new Address
{
Id = 1,
Street = "1st Street",
Users = new List<User>()
{
new User {Id = 1, FirstName = "John", LastName = "Doe"},
new User {Id = 1, FirstName = "Marry", LastName = "Doe"}
}
},
new Address
{
Id = 2,
Street = "2nd Street",
Users = new List<User>()
{
new User {Id = 1, FirstName = "Eric", LastName = "Newton"},
new User {Id = 1, FirstName = "John", LastName = "Newton"}
}
}
};
ParentRepeater.DataBind();
}
}
protected void ParentRepeater_ItemDataBound(object sender, RepeaterItemEventArgs e)
{
if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem)
{
var address = e.Item.DataItem as Address;
var streetLabel = e.Item.FindControl("StreetLabel") as Label;
streetLabel.Text = address.Street;
var repeater = e.Item.FindControl("ChildRepeater") as Repeater;
repeater.ItemDataBound += ChildRepeater_ItemDataBound;
repeater.DataSource = address.Users;
repeater.DataBind();
}
}
protected void ChildRepeater_ItemDataBound(object sender, RepeaterItemEventArgs e)
{
if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem)
{
var user = e.Item.DataItem as User;
var firstNameLabel = e.Item.FindControl("FirstNameLabel") as Label;
firstNameLabel.Text = user.FirstName;
var lastNameLabel = e.Item.FindControl("LastNameLabel") as Label;
lastNameLabel.Text = user.LastName;
}
}
Solution for Original Question
Delete public override void DataBind() event and bind repeaters2 inside PreRender event.
public partial class WebUserControl1 : System.Web.UI.UserControl
{
protected override void OnPreRender(EventArgs e)
{
repeater2.DataSource = DataSource;
repeater2.DataBind();
base.OnPreRender(e);
}
}
I've created a custom Image Field Template which works fine. I decided to create some kind of validation for image sizes so I've created a custom validation attribute. here is the code:
public class ImageSizeValidator : ValidationAttribute
{
public long MaxSize { get; set; }
public long MinSize { get; set; }
public override bool IsValid(object value)
{
if (value == null)
return true;
byte[] image = (byte[]) value;
if (image.Length / 1024L > MaxSize || image.Length / 1024L < MinSize)
return false;
return true;
}
}
and here is my FieldTemplate Image_Edit.ascx:
<%# Control Language="C#" AutoEventWireup="true" CodeBehind="Image_Edit.ascx.cs" Inherits="RastinArgham.CRM.Web.DynamicData.FieldTemplates.Image_Edit" %>
<asp:FileUpload ID="FileUpload1" runat="server" OnDataBinding="FileUpload1DataBinding" />
<asp:RequiredFieldValidator runat="server" ID="RequiredFieldValidator1" CssClass="DDControl DDValidator" ControlToValidate="FileUpload1" Display="Static" Enabled="false" />
<asp:DynamicValidator runat="server" ID="DynamicValidator1" CssClass="DDControl DDValidator" ControlToValidate="FileUpload1" Display="Static" />
and here is Image_Edit.ascx.cs:
public partial class Image_Edit : System.Web.DynamicData.FieldTemplateUserControl
{
protected void Page_Load(object sender, EventArgs e)
{
SetUpValidator(RequiredFieldValidator1);
SetUpValidator(DynamicValidator1);
}
protected override void ExtractValues(IOrderedDictionary dictionary)
{
if (FileUpload1.PostedFile == null || String.IsNullOrEmpty(FileUpload1.PostedFile.FileName) || FileUpload1.PostedFile.InputStream.Length == 0)
return;
dictionary[Column.Name] = FileUpload1.FileBytes;
}
public override Control DataControl
{
get
{
return FileUpload1;
}
}
}
and finally my entity meta data class:
[Display(Name = "ServicePhoto", Order = 410, GroupName = "Misc")]
[HideColumnIn(PageTemplate.List)]
[UIHint("Image")]
[ImageSizeValidator(ErrorMessage = "Invalid Photo Size", MinSize = 30, MaxSize = 300)]
public object ServicePhoto { get; set; }
There are two problems:
1- when IsValid(object value) called value is always null!
2- when trying to upload a new image I always get "The value is not valid" Error on client side of
validation.
I am new to .NET. I am trying to bind a generic List to a GridView in the aspx page. I set AutoGenerateColumns="false", I defined the columns on my .aspx page, and bound them but it's still throwing the error error A field or property with the name 'Assigned' was not found on the selected data source.
I tried all options but end up no where. CL is an alias for my namespace.
SITESTATUS CLASS
public class SiteStatus
{
public string Opened;
public string Assigned;
public string LocationAddress;
public string LocationId;
public SiteStatus(string Assigned, string Opened, string LocationAddress, string LocationId)
{
this.Assigned = Assigned;
this.Opened = Opened;
this.LocationAddress = LocationAddress;
this.LocationId = LocationId;
}
}
Aspx File
<%# Page Language="C#" AutoEventWireup="true" CodeBehind="SiteSurveyStatus.aspx.cs" MasterPageFile="~/Site.Master" Inherits="Website.WebForms.SiteSurveyStatus" %>
<asp:Content ContentPlaceHolderID="ContentPlaceHolder1" runat="server">
<form id="form1" runat="server">
<asp:Label ID="SiteSurvey" runat="server" Text="Site Survey Status" Font-Bold="True"></asp:Label>
<asp:GridView ID="GridView1" runat="server" PageSize="15" CellPadding="0" Width="100%" AutoGenerateColumns="false" EnableViewState="True">
<Columns>
<asp:BoundField HeaderText="Assigned" DataField="Assigned" SortExpression="Assigned" />
<asp:BoundField HeaderText="Opened" DataField="Opened" SortExpression="Opened" />
<asp:BoundField HeaderText="Location" DataField="LocationAddress" />
<asp:BoundField HeaderText="LocationId" DataField="LocationId" />
</Columns>
</asp:GridView>
</form>
Code Behind:
protected void Page_Load(object sender, EventArgs e)
{
List<CL.SiteStatus> list = new List<CL.SiteStatus>();
list.Add(new CL.SiteStatus("09/12/2011", "User123", "Dallas TX 75724", "USATX75724"));
list.Add(new CL.SiteStatus("10/11/2011", "User234", "Houston TX 77724", "USATX77724"));
list.Add(new CL.SiteStatus("02/30/2011", "User567", "Austin TX 70748", "USATX70748"));
list.Add(new CL.SiteStatus("03/01/2011", "User1234", "El Paso TX 71711", "USATX71711"));
list.Add(new CL.SiteStatus("04/02/2011", "User125", "Chicago IL 33456", "USAIL33456"));
GridView1.DataSource = list.ToList();
GridView1.DataBind();
}
The problem looks like it lies with your SiteStatus class. You have properties but no modifiers, so no external code can access them.
Try:
public class SiteStatus
{
public string Opened { get; set; }
public string Assigned { get; set; }
public string LocationAddress { get; set; }
public string LocationId { get; set; }
public SiteStatus(string Assigned, string Opened, string LocationAddress, string LocationId)
{
this.Assigned = Assigned;
this.Opened = Opened;
this.LocationAddress = LocationAddress;
this.LocationId = LocationId;
}
}
The rest of your markup looks fine to me.
I am a newbie in NHibernate.I am facing problem in mapping file.I have 2 tables Fetures and Priority.
Feature FeatureID(PK),FeatureName,PriorityID(FK)
Priorty PriorityID(PK),PriorityName
I want to bind a grid to Feature table but but grid should contain PriorityName rather than PriorityID.
I have tried one-to-one,many-to-one and bag.
Please help me how can write mapping file so that I can get PriorityName for particular PriorityID in Feature class.
I know it is a very simple question.But nothing worked for me. After lots of googling I am posting here.
Please help me
Thanks in Advance
Here's a sample using Fluent NHibernate and SQLite:
using System.Data;
using System.IO;
using FluentNHibernate.Cfg;
using FluentNHibernate.Cfg.Db;
using FluentNHibernate.Mapping;
using NHibernate;
public class Priority
{
public virtual int Id { get; set; }
public virtual string Name { get; set; }
}
public class Feature
{
public virtual int Id { get; set; }
public virtual string Name { get; set; }
public virtual Priority Priority { get; set; }
}
public class PriorityMap : ClassMap<Priority>
{
public PriorityMap()
{
WithTable("Priority");
Id(x => x.Id, "PriorityID");
Map(x => x.Name, "PriorityName");
}
}
public class FeatureMap : ClassMap<Feature>
{
public FeatureMap()
{
WithTable("Feature");
Id(x => x.Id, "FeatureID");
Map(x => x.Name, "FeatureName");
References<Priority>(x => x.Priority, "PriorityID");
}
}
public static class SessionFactoryEx
{
private const string _dbFile = #"C:\data.db3";
static SessionFactoryEx()
{
if (File.Exists(_dbFile))
{
File.Delete(_dbFile);
}
using (var factory = SessionFactoryEx.GetSessionFactory())
using (var connection = factory.ConnectionProvider.GetConnection())
{
SessionFactoryEx.ExecuteQuery("create table Priority(PriorityID int, PriorityName string)", connection);
SessionFactoryEx.ExecuteQuery("create table Feature(FeatureID int, FeatureName string, PriorityID int)", connection);
SessionFactoryEx.ExecuteQuery("insert into Priority (PriorityID, PriorityName) values (1, 'p1')", connection);
SessionFactoryEx.ExecuteQuery("insert into Feature (FeatureID, FeatureName, PriorityID) values (1, 'f1', 1)", connection);
SessionFactoryEx.ExecuteQuery("insert into Feature (FeatureID, FeatureName, PriorityID) values (2, 'f2', 1)", connection);
SessionFactoryEx.ExecuteQuery("insert into Feature (FeatureID, FeatureName, PriorityID) values (3, 'f3', 1)", connection);
}
}
private static ISessionFactory _sessionFactory = null;
public static ISessionFactory GetSessionFactory()
{
if (_sessionFactory == null)
{
_sessionFactory = CreateSessionFactory();
}
return _sessionFactory;
}
private static ISessionFactory CreateSessionFactory()
{
return Fluently.Configure()
.Database(
SQLiteConfiguration.Standard.UsingFile(_dbFile).ShowSql()
)
.Mappings(
m => m.FluentMappings.AddFromAssemblyOf<Priority>()
).BuildSessionFactory();
}
public static void ExecuteQuery(string sql, IDbConnection connection)
{
using (var command = connection.CreateCommand())
{
command.CommandText = sql;
command.ExecuteNonQuery();
}
}
}
And in your ASPX page you can bind data:
<%# Page Language="C#" AutoEventWireup="true" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<script runat="server">
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
using (var factory = SessionFactoryEx.GetSessionFactory())
using (var session = factory.OpenSession())
using (var tx = session.BeginTransaction())
{
var features = session.CreateCriteria(typeof(Feature)).List<Feature>();
featuresGrid.DataSource = features;
featuresGrid.DataBind();
}
}
}
</script>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>Untitled Page</title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:GridView ID="featuresGrid" runat="server" AutoGenerateColumns="false">
<Columns>
<asp:TemplateField HeaderText="Id">
<ItemTemplate>
<%# Eval("Id") %>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Name">
<ItemTemplate>
<%# Eval("Name") %>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Priority Name">
<ItemTemplate>
<%# Eval("Priority.Name") %>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
</div>
</form>
</body>
</html>