Uploading file using Managed client object model in sharepoint 2013 - c#

I have devloped the file uploading into document library in sharepoint 2013 using Managed client object model.
Here iS my upload.aspx
<%# Page Language="C#" AutoEventWireup="true" CodeBehind="WebForm1.aspx.cs" Inherits="WebApplication7.WebForm1" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div>
<table>
<tr>
<td colspan="2" align="center">
<asp:Label Font-Bold="true" Text="Upload a documents to SharePoint 2013" runat="server" ID="lblSharePoint" />
</td>
</tr>
<tr>
<td></td>
</tr>
<tr>
<td>
<asp:Label ID="lblLocalPath" runat="server" Text="Local Path:"></asp:Label>
</td>
<td>
<asp:FileUpload ID="FileLocalPath" Width="350" runat="server" />
</td>
</tr>
<tr>
<td>
<asp:Label ID="lblSharePointURL" runat="server" Text="SharePoint Site URL:"></asp:Label>
</td>
<td>
<asp:TextBox ID="txtSharePointURL" Width="350" runat="server"></asp:TextBox>
</td>
</tr>
<tr>
<td>
<asp:Label ID="lblLibraryName" runat="server" Text="Library Name:"></asp:Label>
</td>
<td>
<asp:TextBox ID="txtLibraryName" Width="350" runat="server"></asp:TextBox>
</td>
</tr>
<tr>
<td colspan="2" align="right">
<asp:Button ID="btnUpload" runat="server" Text="Upload" OnClick="btnUpload_Click" />
</td>
</tr>
<tr>
<td colspan="2">
<asp:Label ID="lblMsg" runat="server" Text=""></asp:Label>
</td>
</tr>
</table>
</div>
</form>
</body>
</html>
and here is my upload.aspx.cs
using Microsoft.SharePoint.Client;
using System;
using System.Collections.Generic;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Net;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace WebApplication7
{
public partial class WebForm1 : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
public ClientContext SPClientContext { get; set; }
public Web SPWeb { get; set; }
public string SPErrorMsg { get; set; }
protected void btnUpload_Click(object sender, EventArgs e)
{
try
{
string sURL = txtSharePointURL.Text;
string sDocName = string.Empty;
if (!string.IsNullOrWhiteSpace(sURL) && !string.IsNullOrWhiteSpace(txtLibraryName.Text) && (FileLocalPath.HasFile))
{
bool bbConnected = Connect(sURL, "abhishekr", "A123bhishek", "saras");
if (bbConnected)
{
Uri uri = new Uri(sURL);
string sSPSiteRelativeURL = uri.AbsolutePath;
sDocName = UploadFile(FileLocalPath.FileContent, FileLocalPath.FileName, sSPSiteRelativeURL, txtLibraryName.Text);
if (!string.IsNullOrWhiteSpace(sDocName))
{
lblMsg.Text = "The document " + sDocName + " has been uploaded successfully..";
lblMsg.ForeColor = Color.Blue;
}
else
{
lblMsg.Text = SPErrorMsg;
lblMsg.ForeColor = Color.Red;
}
}
}
}
catch (Exception ex)
{
Response.Write(ex.Message.ToString());
}
}
public bool Connect(string SPURL, string SPUserName, string SPPassWord, string SPDomainName)
{
bool bConnected = false;
try
{
SPClientContext = new ClientContext(SPURL);
SPClientContext.Credentials = new NetworkCredential(SPUserName, SPPassWord, SPDomainName);
SPWeb = SPClientContext.Web;
SPClientContext.Load(SPWeb);
SPClientContext.ExecuteQuery();
bConnected = true;
}
catch (Exception ex)
{
bConnected = false;
SPErrorMsg = ex.Message;
Response.Write(ex.Message.ToString());
}
return bConnected;
}
public string UploadFile(Stream fs, string sFileName, string sSPSiteRelativeURL, string sLibraryName)
{
string sDocName = string.Empty;
try
{
if (SPWeb != null)
{
var sFileUrl = String.Format("{0}/{1}/{2}", sSPSiteRelativeURL, sLibraryName, sFileName);
Microsoft.SharePoint.Client.File.SaveBinaryDirect(SPClientContext, sFileUrl, fs, true);
sDocName = sFileName;
}
}
catch (Exception ex)
{
sDocName = string.Empty;
SPErrorMsg = ex.Message;
Response.Write(ex.Message.ToString());
}
return sDocName;
}
}
}
it is working fine when i am uploading small files, it through an error when i uploading large file.
Error:" Maximum request length exceeded "
Please, help me how to resolve issue.

you can define max request length in SharePoint like this:
https://blogs.technet.microsoft.com/sammykailini/2013/11/06/how-to-increase-the-maximum-upload-size-in-sharepoint-2013/
In Central Admin>Application Management>Manage Web Applications> Select the desired web app and click General Settings on the ribbon
In web.config edit httpRuntime Node like this (for 2GB files and unlimited execution):

Related

Select multiple files at a time using FileUpload control in asp.net

Here's my code
protected void Page_Load(object sender, EventArgs e)
{
tbusrcompdate.Attributes.Add("readonly", "readonly");
if (!IsPostBack)
{
//using session state
if (Session["userid"] == null)
{
Session["userid"] = "Compliance_Tracker";
lblsessionID.Text = Session["userid"].ToString();
}
else
{
lblsessionID.Text = Session["userid"].ToString();
}
//populating ddlTaskId
string query = "select * from Compliance_Tracker.dbo.tasklistManager where STATUS='1';";
string columnname = "TASK ID";
string datavaluefield = "TASK ID";
obj7.PopulateCombo(ddlTaskID, query, columnname, datavaluefield);
//default values in labels
string query1 = "select top 1 [DESC] from Compliance_Tracker.dbo.tasklistManager where STATUS = '1';";
lblDescOutput.Text = obj7.ExecuteScalar(query1).ToString();
string query2 = "select top 1 FREQUENCY from Compliance_Tracker.dbo.tasklistManager where STATUS = '1';";
lblFrequencyOutput.Text = obj7.ExecuteScalar(query2).ToString();
}
}
protected void ddlTaskID_SelectedIndexChanged(object sender, EventArgs e)
{
string selectedtext = ddlTaskID.SelectedValue.ToString();
string query = "select [DESC] from Compliance_Tracker.dbo.tasklistManager where Compliance_Tracker.dbo.tasklistManager.[TASK ID] ='" + selectedtext + "';";
lblDescOutput.Text = obj7.ExecuteScalar(query).ToString();
}
protected void btnAdd_Click(object sender, EventArgs e)
{
}
protected void Button1_Click(object sender, EventArgs e)
{
if (fuDocpath.HasFiles)
{
try
{
DateTime now = DateTime.Now;
lbldateStamp.Text = now.ToString("mm_dd_yyyy_hh_mm_ss");
string basicPath = Server.MapPath("~/Uploaded_Files/");
string foldername = lblsessionID.Text + "_" + lbldateStamp.Text;
string folderpath = (basicPath + foldername + "/");
Directory.CreateDirectory(folderpath);
foreach (HttpPostedFile file in fuDocpath.PostedFiles)
{
string filename = Path.GetFileName(fuDocpath.FileName);
string folderpath1 = folderpath + "/";
fuDocpath.SaveAs(folderpath1 + filename);
lblName.Text = lblName.Text+"|" + filename;
lblerror.Text = string.Empty;
}
}
catch (Exception ex)
{
lblerror.Text = "File couldn't be uploaded." + ex.Message;
lblName.Text = string.Empty;
}
}
}
Now , using the above code I am only able to do single selection even though I can upload multiple files totally. So I need to know ,if there's a way to select multiple files at a time using fileupload tool OR will I have to use any other tool?
Here's my aspx code
<asp:Content ID="Content1" ContentPlaceHolderID="ContentPlaceHolder3" Runat="Server">
<form id="Form1" runat="server" style="border-style: none; border-width: inherit; border-color: #008000; background-color:#33CC33; height:588px; width:669px; background-image: url('new.jpg'); background-repeat: no-repeat;" method="post" enctype="multipart/form-data">
<h1 style="height: 34px">
TRANSACTION MANAGER TABLE
</h1>
<asp:ScriptManager ID="ScriptManager1" runat="server"></asp:ScriptManager>
<asp:Label ID="lblsessionID" runat="server" Text=""></asp:Label>
<asp:Label ID="lbldateStamp" runat="server" Text=""></asp:Label>
<table id="table1" style="border-style: none; height:188px; width:549px; margin-left:30px; border-collapse: collapse; margin-top: 0px;">
<tr>
<td style="width: 137px; height:30px;"><asp:Label ID="lblTaskID" runat="server" Text="TASK ID" Width="70px"></asp:Label></td>
<td style="height:30px"><asp:DropDownList ID="ddlTaskID" runat="server" Height="20px" style="margin-left: 50px" Width="126px" OnSelectedIndexChanged="ddlTaskID_SelectedIndexChanged" AutoPostBack="true" ></asp:DropDownList></td>
</tr>
<tr>
<td style="width:137px; height:30px;"><asp:Label ID="lblDesc" runat="server" Text="DESC" Width="70px"></asp:Label></td>
<td style ="height:30px"><asp:Label ID="lblDescOutput" runat="server" style="margin-left:50px" Width="126px" Height="20px"></asp:Label></td>
</tr>
<tr>
<td style="width: 137px; height:30px;"><asp:Label ID="lblFrequency" runat="server" Text="FREQUENCY" Width="132px"></asp:Label></td>
<td style="height:30px"><asp:Label ID="lblFrequencyOutput" runat="server" style="margin-left:50px" Width="126px" Height="20px"></asp:Label></td>
</tr>
<tr>
<td style="width: 137px; height:30px;"><asp:Label ID="lblDocpath" runat="server" Text="DOC PATH" Width="107px"></asp:Label></td>
<td style="height:30px">
<asp:FileUpload ID="fuDocpath" runat="server" AllowMultiple="true" />
<asp:Button ID="Button1" runat="server" Text ="Upload File" OnClick="Button1_Click" />
<asp:Label ID="lblerror" runat="server" Text="" style="margin-left: 50px"></asp:Label>
<asp:Label ID="lblName" runat="server" Text=""></asp:Label>
</td>
</tr>
<tr>
<td style="width: 137px; height:30px;"><asp:Label ID="lblusrcompdate" runat="server" Text="USER COMPLETE DATE" Width="147px"></asp:Label></td>
<td style="height:30px"><asp:TextBox ID="tbusrcompdate" runat="server"></asp:TextBox>
<asp:ImageButton ID ="imgbtncalender" runat="server" ImageUrl="~/home-calendar-button.jpg" Height="17px" style="margin-left: 16px" Width="16px" />
<asp:CalendarExtender ID="CalendarExtender1" runat="server" TargetControlID="tbusrcompdate" Format="dd/MM/yyyy" PopupButtonID="imgbtncalender"></asp:CalendarExtender>
</td>
</tr>
</table><br />
<asp:Button ID="btnAdd" runat="server" Text="ADD" Height="27px" Width="80px" style="margin-left:235px" OnClick="btnAdd_Click"/>
</form>
The actual problem was with IE and after updation Iam able to select multiple files now.
Another problem was with my code actually only one file was getting selected because I didn't get the file name properly. Well , it was with the code actually that in the part where I declared the filename string
foreach (HttpPostedFile files in fuDocpath.PostedFiles)
{
string filename = Path.GetFileName(fuDocpath.FileName);
string folderpath1 = folderpath + "/";
fuDocpath.SaveAs(folderpath1 + filename);
lblName.Text = lblName.Text+"|" + filename;
lblerror.Text = string.Empty;
}
Now, here the main problem was I wasn't getting the proper filename . SO , the mistake was
string filename = Path.GetFileName(files.Filename)
instead of fuDocpath.filename.
Silly mistake fml!!!
This is not exactly the answer for your specific code. But it is an alternative to upload multiple files.
For uploading multiple files, I don't do all this stuff, but there is something called as asp:AjaxFileUpload control for this
<asp:AjaxFileUpload ID="AjaxFileUpload1" ToolTip="Uplaod File" OnUploadComplete="AjaxFileUpload1_UploadComplete" runat="server" />
Code Behind :
protected void AjaxFileUpload1_UploadComplete(object sender, AjaxControlToolkit.AjaxFileUploadEventArgs e)
{
try
{
string str = System.IO.Path.GetFileName(e.FileName);
string fullpath = Path.GetFullPath(str);
string str1 = "Your insert Query";
con.Open();
cmd = new SqlCommand(str1, con);
// your command parameters to add
cmd.Parameters.AddWithValue("#Image_Caption", str);
cmd.Parameters.AddWithValue("#Image_Path", "Images/" + str);
cmd.Parameters.AddWithValue("#Image_Name", str);
cmd.ExecuteNonQuery();
con.Close();
string filePath = Server.MapPath("~/Images/") + System.IO.Path.GetFileName(e.FileName);
AjaxFileUpload1.SaveAs(filePath);
}
catch (Exception eep)
{
throw;
}
}

all data disappears after PostBack

So on a textbox I will write how many dropdownlists, textboxes, label etc and the page ia AutoPostBack. But after I choose an item on a gridview, the page ia autopostback and all the data dissapear. I want gridview to be AutoPostBack but how can I make it not to dissapear all the other item I have added from the first textbox?
For more info here is the source code:
Default.aspx
<%# Page Language="C#" AutoEventWireup="true" CodeFile="Default2.aspx.cs" Inherits="Default2" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
<style type="text/css">
.auto-style1 {
width: 248px;
}
.auto-style2 {
width: 253px;
}
</style>
</head>
<body>
<form id="form1" runat="server">
<asp:ScriptManager ID="ScriptManager1" runat="server" />
<div>
<table style="width:100%;">
<tr>
<td class="auto-style2">
</td>
<td>
</td>
</tr>
<tr>
<td class="auto-style1"> </td>
<td class="auto-style2">
<asp:TextBox ID="TextBox1" runat="server" AutoPostBack="True" OnTextChanged="TextBox1_TextChanged"></asp:TextBox>
</td>
<td> </td>
</tr>
<tr>
<td class="auto-style1"> </td>
<td class="auto-style2">
<asp:PlaceHolder ID="PlaceHolder1" runat="server"></asp:PlaceHolder>
</td>
<td> </td>
</tr>
<tr>
<td class="auto-style1"> </td>
<td class="auto-style2">
<asp:PlaceHolder ID="PlaceHolder2" runat="server"></asp:PlaceHolder>
</td>
<td> </td>
</tr>
<tr>
<td class="auto-style1"> </td>
<td class="auto-style2">
<asp:PlaceHolder ID="PlaceHolder3" runat="server"></asp:PlaceHolder>
</td>
<td> </td>
</tr>
<tr>
<td class="auto-style1"> </td>
<td class="auto-style2">
<asp:PlaceHolder ID="PlaceHolder4" runat="server"></asp:PlaceHolder>
</td>
<td> </td>
</tr>
<tr>
<td class="auto-style1"> </td>
<td class="auto-style2">
<asp:PlaceHolder ID="PlaceHolder5" runat="server"></asp:PlaceHolder>
</td>
<td> </td>
</tr>
<tr>
<td class="auto-style1"> </td>
<td class="auto-style2">
</td>
<td> </td>
</tr>
</table>
<br />
</div>
</form>
</body>
</html>
and Default.aspx.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data.SqlClient;
using System.Configuration;
using System.Data;
public partial class Default2 : System.Web.UI.Page
{
DropDownList artikulli;
TextBox cmimi;
Label tregoCmimi;
TextBox sasia;
Label cmimiGjithsej;
protected void Page_Load(object sender, EventArgs e)
{
if (Page.IsPostBack)
{
}
}
protected void TextBox1_TextChanged(object sender, EventArgs e)
{
if (!string.IsNullOrEmpty(TextBox1.Text))
{
int a = int.Parse(TextBox1.Text);
for (int j = 1; j <= a; j++)
{
Guid IDUnik = new Guid();
artikulli = new DropDownList();
cmimi = new TextBox();
tregoCmimi = new Label();
sasia = new TextBox();
cmimiGjithsej = new Label();
artikulli.ID = j.ToString(IDUnik.ToString("N").Substring(31));
artikulli.AutoPostBack = true;
cmimi.ID = j.ToString(IDUnik.ToString("D").Substring(30));
tregoCmimi.ID = j.ToString(IDUnik.ToString("P"));
sasia.ID = j.ToString(j.ToString(IDUnik.ToString("X")));
cmimiGjithsej.ID = j.ToString(j.ToString(IDUnik.ToString("B"))); ;
PlaceHolder1.Controls.Add(artikulli);
PlaceHolder2.Controls.Add(cmimi);
PlaceHolder3.Controls.Add(tregoCmimi);
PlaceHolder4.Controls.Add(sasia);
PlaceHolder5.Controls.Add(cmimiGjithsej);
artikulli.Items.Insert(0, new ListItem("<Select Subject>", "0"));
artikulli.Items.Insert(1, new ListItem("<Select Subject>", "1"));
}
}
}
}
you can do as below
protected void Page_Load(object sender, EventArgs e)
{
if (Page.IsPostBack)
{
AddItems();
}
}
private void AddItems()
{
if (!string.IsNullOrEmpty(TextBox1.Text))
{
int a = int.Parse(TextBox1.Text);
for (int j = 1; j <= a; j++)
{
Guid IDUnik = new Guid();
artikulli = new DropDownList();
cmimi = new TextBox();
tregoCmimi = new Label();
sasia = new TextBox();
cmimiGjithsej = new Label();
artikulli.ID = j.ToString(IDUnik.ToString("N").Substring(31));
artikulli.AutoPostBack = true;
cmimi.ID = j.ToString(IDUnik.ToString("D").Substring(30));
tregoCmimi.ID = j.ToString(IDUnik.ToString("P"));
sasia.ID = j.ToString(j.ToString(IDUnik.ToString("X")));
cmimiGjithsej.ID = j.ToString(j.ToString(IDUnik.ToString("B"))); ;
PlaceHolder1.Controls.Add(artikulli);
PlaceHolder2.Controls.Add(cmimi);
PlaceHolder3.Controls.Add(tregoCmimi);
PlaceHolder4.Controls.Add(sasia);
PlaceHolder5.Controls.Add(cmimiGjithsej);
artikulli.Items.Insert(0, new ListItem("<Select Subject>", "0"));
artikulli.Items.Insert(1, new ListItem("<Select Subject>", "1"));
}
}
}
you don't need OnTextChanged="TextBox1_TextChanged" in your textbox
protected void Page_Load(object sender, EventArgs e)
{
if (Page.IsPostBack)
{
Populate();
}
}
protected void TextBox1_TextChanged(object sender, EventArgs e)
{
Populate();
}
void Populate()
{
PlaceHolder1.Controls.Clear();
PlaceHolder2.Controls.Clear();
PlaceHolder3.Controls.Clear();
PlaceHolder4.Controls.Clear();
PlaceHolder5.Controls.Clear();
if (!string.IsNullOrEmpty(TextBox1.Text))
{
int a = int.Parse(TextBox1.Text);
for (int j = 1; j <= a; j++)
{
Guid IDUnik = new Guid();
artikulli = new DropDownList();
cmimi = new TextBox();
tregoCmimi = new Label();
sasia = new TextBox();
cmimiGjithsej = new Label();
artikulli.ID = j.ToString(IDUnik.ToString("N").Substring(31));
artikulli.AutoPostBack = true;
cmimi.ID = j.ToString(IDUnik.ToString("D").Substring(30));
tregoCmimi.ID = j.ToString(IDUnik.ToString("P"));
sasia.ID = j.ToString(j.ToString(IDUnik.ToString("X")));
cmimiGjithsej.ID = j.ToString(j.ToString(IDUnik.ToString("B"))); ;
PlaceHolder1.Controls.Add(artikulli);
PlaceHolder2.Controls.Add(cmimi);
PlaceHolder3.Controls.Add(tregoCmimi);
PlaceHolder4.Controls.Add(sasia);
PlaceHolder5.Controls.Add(cmimiGjithsej);
artikulli.Items.Insert(0, new ListItem("<Select Subject>", "0"));
artikulli.Items.Insert(1, new ListItem("<Select Subject>", "1"));
}
}
}

background image disappears after using button in postbacktrigger of update panel in asp.net

Background image disappears after using button in postbacktrigger of update panel in asp.net.I have designed registraion form and have placed all controls in update panel.After clicking on submit button,data gets submitted ,the page refreshes and background image dissappears.The values are getting properly inserted in database.
PFB the HTML code for Registration.aspx:-
<%# Page Title="" Language="C#" MasterPageFile="~/Site.master" AutoEventWireup="true" CodeFile="Register.aspx.cs" Inherits="Register" %>
<%# Register Assembly="AjaxControlToolkit" Namespace="AjaxControlToolkit" TagPrefix="asp" %>
<%# Register Src="~/UserControls/FacebookUserControl.ascx" TagName="facebookheader" TagPrefix="Uc1"%>
<asp:Content ID="Content1" ContentPlaceHolderID="head" Runat="Server">
<style type="text/css">
.auto-style1 {
width: 100%;
}
</style>
<script type="text/javascript">
function HideCtrl(ctrl, timer) {
var ctry_array = ctrl.split(",");
var num = 0, arr_length = ctry_array.length;
while (num < arr_length) {
if (document.getElementById(ctry_array[num])) {
setTimeout('document.getElementById("' + ctry_array[num] + '").style.display = "none";', timer);
}
num += 1;
}
return false;
}
</script>
<script>
$(function () {
// Initialize Backgound Stretcher
$('BODY').bgStretcher({
images: ['images/slide-1.jpg'],
imageWidth: 1600,
imageHeight: 964,
resizeProportionally: true
});
});
</script>
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="ContentPlaceHolder1" Runat="Server">
<form id="form1" runat="server">
<asp:ToolkitScriptManager ID="ToolkitScriptManager1" runat="server"></asp:ToolkitScriptManager>
<section id="content">
<div class="main-block">
<div class="container_12">
<div class="wrapper">
<table>
<tr>
<td>
<asp:ValidationSummary ID="ValidationSummary1" runat="server" ValidationGroup="vg1" HeaderText="Fields marked with (*) are required"
ForeColor="Red" CssClass="error" />
</td>
</tr>
<tr>
<td>
<div id="divErrorMess" runat="server" visible="false" class="mess">
<asp:Label ID="lblMessage" runat="server" ForeColor="Red" Visible="False"></asp:Label>
</div>
<div id="divBallon" runat="server" visible="false" class="mess">
<div>
<asp:Label ID="lblMessage2" runat="server" Visible="False" ForeColor="Red"></asp:Label>
</div>
</div>
</td>
</tr>
</table>
<asp:UpdatePanel ID="UpdatePanel1" runat="server" UpdateMode="Conditional">
<ContentTemplate>
<table style="width:358px; border:0;">
<tr>
<td> Full Name</td>
</tr>
<tr>
<td> <asp:TextBox ID="txtFullName" runat="server" placeholder="Enter your Full Name" ValidationGroup="vg1" Width="250px"></asp:TextBox>
<span style="color:red">*</span>
<asp:RequiredFieldValidator ID="rfvFullName" runat="server" ErrorMessage=""
ControlToValidate="txtFullName" Display="None" ForeColor="Red" SetFocusOnError="True"
ValidationGroup="vg1"></asp:RequiredFieldValidator>
</td>
</tr>
<tr>
<td> Date Of Birth</td>
</tr>
<tr>
<td> <%--<asp:TextBox ID="txtDateOfBirth" runat="server" placeholder="Enter your Date Of Birth" ValidationGroup="vg1" Width="250px" ClientIDMode="Static">
</asp:TextBox>--%><%-- <span style="color:red">*</span> <asp:CalendarExtender ID="CalendarExtender1" runat="server" Format="MM-dd-yyyy"
TargetControlID="txtDateOfBirth"></asp:CalendarExtender>--%><%-- <asp:RequiredFieldValidator ID="rfvDob" runat="server" ErrorMessage=""
ControlToValidate="txtDateOfBirth" Display="None" ForeColor="Red" SetFocusOnError="True"
ValidationGroup="vg1"></asp:RequiredFieldValidator>--%><asp:DropDownList ID="ddlMonth" runat="server" OnSelectedIndexChanged="ddlMonth_SelectedIndexChanged" placeholder="Month" AutoPostBack="true">
</asp:DropDownList> <span style="color:red">*</span>
<asp:RequiredFieldValidator ID="rfvMonth"
runat="server" ErrorMessage="*" ControlToValidate="ddlMonth" ForeColor="Red"
SetFocusOnError="True" ValidationGroup="vg1"></asp:RequiredFieldValidator>
<asp:DropDownList ID="ddlDate" runat="server" AutoPostBack="true">
</asp:DropDownList> <span style="color:red">*</span>
<asp:RequiredFieldValidator ID="rfvDate"
runat="server" ErrorMessage="*" ControlToValidate="ddlDate" ForeColor="Red"
SetFocusOnError="True" ValidationGroup="vg1"></asp:RequiredFieldValidator>
<asp:DropDownList ID="ddlYear" runat="server" OnSelectedIndexChanged="ddlYear_SelectedIndexChanged" AutoPostBack="true">
</asp:DropDownList> <span style="color:red">*</span>
<asp:RequiredFieldValidator ID="rfvYear" runat="server"
ErrorMessage="*"
ForeColor="Red" SetFocusOnError="True" ValidationGroup="vg1"
ControlToValidate="ddlYear"></asp:RequiredFieldValidator>
</td>
</tr>
<tr>
<td> Phone Number</td>
</tr>
<tr>
<td> <asp:TextBox ID="txtPhoneNumber" runat="server" placeholder="Enter your Phone Number" ValidationGroup="vg1" Width="250px">
</asp:TextBox>
<span style="color:red">*</span>
<asp:RequiredFieldValidator ID="rfvPhone" runat="server" ErrorMessage=""
ControlToValidate="txtPhoneNumber" Display="None" ForeColor="Red" SetFocusOnError="True"
ValidationGroup="vg1"></asp:RequiredFieldValidator>
<asp:RegularExpressionValidator ID="revPhone" runat="server" ErrorMessage="Enter only 10 digit number"
ControlToValidate="txtPhoneNumber" Display="None" ForeColor="Red" SetFocusOnError="True"
ValidationExpression="^[0-9]{10}" ValidationGroup="vg1"></asp:RegularExpressionValidator>
</td>
</tr>
<tr>
<td> Email Address</td>
</tr>
<tr>
<td> <asp:TextBox ID="txtEmail" runat="server" placeholder="Enter your Email address" ValidationGroup="vg1" Width="250px">
</asp:TextBox>
<span style="color:red">*</span>
<asp:RequiredFieldValidator ID="rfvEmail" runat="server" ErrorMessage=""
ControlToValidate="txtEmail" Display="None" ForeColor="Red" SetFocusOnError="True"
ValidationGroup="vg1"></asp:RequiredFieldValidator>
<asp:RegularExpressionValidator ID="revEmail" runat="server" ErrorMessage="Invalid Email!"
ControlToValidate="txtEmail" Display="None" ForeColor="Red" SetFocusOnError="True"
ValidationExpression="\w+([-+.']\w+)*#\w+([-.]\w+)*\.\w+([-.]\w+)*" ValidationGroup="vg1">
</asp:RegularExpressionValidator>
</td>
</tr>
<tr>
<td> Submit 2 Photos</td>
</tr>
<tr>
<td> <asp:FileUpload ID="FileUpload1" runat="server" Width="250px" />
<span style="color:red">*</span>
<asp:RequiredFieldValidator ID="rfvPhoto1" runat="server" ErrorMessage=""
ControlToValidate="FileUpload1" Display="None" ForeColor="Red" SetFocusOnError="True"
ValidationGroup="vg1"></asp:RequiredFieldValidator>
</td>
</tr>
<tr>
<td> <asp:FileUpload ID="FileUpload2" runat="server" Width="250px"/>
<span style="color:red">*</span>
<asp:RequiredFieldValidator ID="rfvPhoto2" runat="server" ErrorMessage=""
ControlToValidate="FileUpload2" Display="None" ForeColor="Red" SetFocusOnError="True"
ValidationGroup="vg1"></asp:RequiredFieldValidator>
</td>
</tr>
<tr>
<td> Terms & Conditions</td>
</tr>
<tr>
<td> <asp:CheckBox ID="chkAgree" runat="server" /> I agree to Terms and Conditions</td>
</tr>
<tr>
<td> <asp:ImageButton ID="btnSubmit" runat="server" ImageUrl="~/images/submit.png" OnClick="btnSubmit_Click" ValidationGroup="vg1" />
<asp:ImageButton ID="btnReset" runat="server" ImageUrl="~/images/reset.png" CausesValidation="False" OnClick="btnReset_Click" />
</td>
</tr>
<tr>
<td> </td>
</tr>
</table>
</ContentTemplate>
<Triggers>
<asp:AsyncPostBackTrigger ControlID="ddlMonth" EventName="SelectedIndexChanged" />
<asp:AsyncPostBackTrigger ControlID="ddlDate" EventName="SelectedIndexChanged" />
<asp:AsyncPostBackTrigger ControlID="ddlYear" EventName="SelectedIndexChanged" />
<asp:PostBackTrigger ControlID="btnSubmit" />
</Triggers>
</asp:UpdatePanel>
</div>
</div>
<div class="sidebar">
<Uc1:facebookheader ID="fbtag" runat="server" />
</div>
</div>
</section>
<%-- </div> --%>
</form>
</asp:Content>
PFB code for Registration.aspx.cs:
The below code contains data for registration.aspx. In the below i have used dropdownlist to enter date as input and necessary validations are performed for date.I have used arraylist to add months and used for loop to add years.Also i have used CheckLeapYear fn to check leap year.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.ComponentModel.DataAnnotations;
using System.Data;
using System.Data.SqlClient;
using System.Configuration;
using System.IO;
using System.Net.Mail;
using System.Collections;
public partial class Register : System.Web.UI.Page
{
int year;
string month;
protected void Page_Load(object sender, EventArgs e)
{
//System.Web.UI.HtmlControls.HtmlGenericControl divmain = (System.Web.UI.HtmlControls.HtmlGenericControl)Master.FindControl("divmain");
//divmain.Attributes.Add("class", "extra-block");
if (!IsPostBack)
{
this.Page.Title = "Register Us With Now to kick start your Career in MatureModelling";
this.Page.MetaDescription =
"MatureModelling connects new faces and models with scouts, international model photo "
+ "shoot and photographers. Casting Directors are now Looking"
+ " For real Models To Front Their Campaigns.";
this.Page.MetaKeywords =
"international photographers, expert model advice";
System.Web.UI.HtmlControls.HtmlGenericControl aRegister = (System.Web.UI.HtmlControls.HtmlGenericControl)Master.FindControl("Register");
aRegister.Attributes.Add("class", "current");
Response.Cache.SetNoStore();
DateTime tnow = DateTime.Now;
ArrayList ayear = new ArrayList();
int i;
for (i = 1970; i <= DateTime.Now.Year; i++)
{
ayear.Add(i);
}
ArrayList amonth = new ArrayList();
amonth.Add("Jan");
amonth.Add("Feb");
amonth.Add("Mar");
amonth.Add("Apr");
amonth.Add("May");
amonth.Add("Jun");
amonth.Add("Jul");
amonth.Add("Aug");
amonth.Add("Sep");
amonth.Add("Oct");
amonth.Add("Nov");
amonth.Add("Dec");
ddlYear.DataSource = ayear;
ddlYear.DataBind();
ddlMonth.DataSource = amonth;
ddlMonth.DataBind();
ddlYear.SelectedValue = tnow.Year.ToString();
ddlMonth.SelectedValue = tnow.Month.ToString();
year = Int32.Parse(ddlYear.SelectedValue);
month = Convert.ToString(ddlMonth.SelectedValue);
BindDays(year, month);
ddlDate.SelectedValue = tnow.Day.ToString();
}
}
#region Button Event
protected void btnSubmit_Click(object sender, ImageClickEventArgs e)
{
lblMessage.Text = "";
string strScript = string.Empty;
string strCtrl = divErrorMess.ClientID;
strScript = "HideCtrl('" + strCtrl + "', '3000')";
try
{
if (chkAgree.Checked)
{
Registration objRegistration = new Registration();
objRegistration.FirstName = txtFullName.Text.Trim().ToString();
//objRegistration.BirthDate = txtDateOfBirth.Text.Trim().ToString();
objRegistration.BirthDate = ddlYear.SelectedItem.Text.ToString()
+ "-" + ddlMonth.SelectedItem.Value.ToString()
+ "-" + ddlDate.SelectedItem.Text.ToString();
objRegistration.EmailId = txtEmail.Text.Trim().ToString();
objRegistration.PhoneNo = txtPhoneNumber.Text.Trim().ToString();
if (FileUpload1.HasFile)
{
objRegistration.Photo1 = DateTime.Now.ToString("ddMMyyyy") + FileUpload1.FileName.ToString();
}
string pathBig = Server.MapPath("~\\ModelPhotos\\" + DateTime.Now.ToString("ddMMyyyy") + FileUpload1.FileName.ToString());
ViewState["pathBig"] = pathBig;
if (File.Exists(pathBig))
{
//File.Delete(pathBig);
FileUpload1.SaveAs(pathBig);
}
else
{
FileUpload1.SaveAs(pathBig);
}
if (FileUpload2.HasFile)
{
objRegistration.Photo2 = DateTime.Now.ToString("ddMMyyyy") + FileUpload2.FileName.ToString();
}
string pathBig1 = Server.MapPath("~\\ModelPhotos\\" + DateTime.Now.ToString("ddMMyyyy")+FileUpload2.FileName.ToString());
ViewState["pathBig1"] = pathBig1;
if (File.Exists(pathBig1))
{
//File.Delete(pathBig1);
FileUpload2.SaveAs(pathBig1);
}
else
{
FileUpload2.SaveAs(pathBig1);
}
if (chkAgree.Checked)
{
objRegistration.IsAgree = "true";
}
else
{
objRegistration.IsAgree = "false";
}
RegistrationOperation objRegisterOperation = new RegistrationOperation();
int k = Convert.ToInt32(objRegisterOperation.InsertRegisterUser(objRegistration));
if (k==0)
{
divErrorMess.Visible = false;
divBallon.Visible = true;
lblMessage2.Visible = true;
lblMessage2.ForeColor = System.Drawing.Color.Green;
lblMessage2.Text = "User Created Successfully!";
lblMessage.Text = string.Empty;
Session["result"] = "insert";
// sendmail();
// sendmailtoadmin();
fnClearControls();
divBallon.Visible = true;
strScript="HideCtrl('"+divBallon.ClientID+"','3000')";
}
else if (k==1)
{
divErrorMess.Visible = true;
lblMessage.Visible = true;
lblMessage.ForeColor = System.Drawing.Color.Red;
lblMessage.Text = "Sorry,Please try again!";
divBallon.Visible = false;
}
else if (k==2)
{
divErrorMess.Visible = true;
lblMessage.Visible = true;
lblMessage.ForeColor = System.Drawing.Color.Blue;
lblMessage.Text = "Email Id already exists!";
divBallon.Visible = false;
}
}
else
{
divErrorMess.Visible = true;
lblMessage.Visible = true;
lblMessage.ForeColor = System.Drawing.Color.Orange;
lblMessage.Text = "Please accept terms & conditions";
divBallon.Visible = false;
}
}
catch (Exception ex)
{
throw ex;
}
Page.ClientScript.RegisterStartupScript(this.GetType(), Guid.NewGuid().ToString(), strScript, true);
}
protected void btnReset_Click(object sender, ImageClickEventArgs e)
{
fnClearControls();
divBallon.Visible = false;
divErrorMess.Visible = false;
}
#endregion
#region Private Method
private void fnClearControls()
{
txtFullName.Text = " ";
//txtLastName.Text = "";
txtPhoneNumber.Text = "";
// txtParentsPhoneNumber.Text = "";
txtEmail.Text = "";
chkAgree.Checked = false;
//txtDateOfBirth.Text = "";
ddlDate.SelectedIndex = 0;
ddlMonth.SelectedIndex = 0;
ddlYear.SelectedValue = Convert.ToString(DateTime.Now.Year);
}
public void FillDays()
{
ddlDate.Items.Clear();
//getting numbner of days in selected month & year
int noofdays = DateTime.DaysInMonth(Convert.ToInt32(ddlYear.SelectedValue), Convert.ToInt32(ddlMonth.SelectedValue));
//Fill days
for (int i = 0; i <= noofdays; i++)
{
ddlDate.Items.Add(i.ToString());
}
ddlDate.Items.FindByValue(System.DateTime.Now.Day.ToString()).Selected = true;
}
private bool CheckLeapYear(int year)
{
if ((year%4==0)&&(year%100!=0)||(year%400==0))
return true;
else return false;
}
private void BindDays(int year, string month)
{
int i;
ArrayList aday = new ArrayList();
switch (month)
{
case "Jan":
case "Mar":
case "May":
case "Jul":
case "Aug":
case "Oct":
case "Dec":
for (i = 1; i <= 31; i++)
{
aday.Add(i);
}
break;
case "Feb":
if (CheckLeapYear(year))
{
for (i = 1; i <= 29; i++)
aday.Add(i);
}
else
{
for (i = 1; i <= 28; i++)
aday.Add(i);
}
break;
case "Apr":
case "Jun":
case "Sep":
case "Nov":
for (i = 1; i <= 30; i++)
aday.Add(i);
break;
}
ddlDate.DataSource = aday;
ddlDate.DataBind();
}
#endregion
Following are dropdownlist events adn BindDays fn is used.
#region DDL events
protected void ddlYear_SelectedIndexChanged(object sender, EventArgs e)
{
year = Int32.Parse(ddlYear.SelectedValue);
month = Convert.ToString(ddlMonth.SelectedValue);
BindDays(year, month);
}
Following are dropdownlist events adn BindDays fn is used.
protected void ddlMonth_SelectedIndexChanged(object sender, EventArgs e)
{
year = Int32.Parse(ddlYear.SelectedValue);
month = Convert.ToString(ddlMonth.SelectedValue);
BindDays(year, month);
}
#endregion
}
It looks like you probably just need to call that JavaScript function that initializes your "Background Stretcher" on each UpdatePanel update (rather than just when the DOM loads). Changing that function to this should do the trick:
function pageLoad() {
$('BODY').bgStretcher({
images: ['images/slide-1.jpg'],
imageWidth: 1600,
imageHeight: 964,
resizeProportionally: true
});
}
Notice that I used function pageLoad() { (should be called on each postback, including AJAX partial postbacks) rather than $(function () { (only called once, when the DOM loads).

How to read user control values?

I want to get values from user control
I tried but loop comes out
Code:
.aspx
<asp:Repeater ID="rpt1" runat="server">
<ItemTemplate>
</ItemTemplate>
</asp:Repeater>
<asp:Button ID="btnSaveVisa" Text="Save" runat="server" OnClick="btnSaveVisa_Click" />
AddVisaUserControl.ascx
<%# Control Language="C#" AutoEventWireup="true" CodeBehind="AddVisaControl.ascx.cs" EnableViewState="false" Inherits="Pyramid.AddVisaControl" %>
<div id="divreg" runat="server">
<table id="tbl" runat="server">
<tr>
<td>
<asp:Label ID="lbl2" runat="server"></asp:Label>
</td>
</tr>
<tr>
<td> Visa Number:</td>
<td><asp:TextBox ID="txtUser" Width="160px" runat="server"/></td>
<td> Country Name:</td>
<td><asp:DropDownList ID="dropCountry" Width="165px" runat="server"></asp:DropDownList></td>
</tr>
<tr>
<td> Type of Visa:</td>
<td><asp:DropDownList ID="dropVisa" Width="165px" runat="server"></asp:DropDownList></td>
<td> Type of Entry:</td>
<td><asp:DropDownList ID="dropEntry" Width="165px" runat="server"></asp:DropDownList></td>
</tr>
<tr>
<td> Expiry Date</td>
<td>
</td>
</tr>
</table>
</div>
.aspx.cs
public void generateControls()
{
for (int i = 0; i < int.Parse(ViewState["ControlCount"].ToString()); i++)
{
Label lbl = new Label();
string count = Convert.ToString(i + 1);
lbl.Text = "Visa" + count;
rpt1.Controls.Add(lbl);
rpt1.Controls.Add(LoadControl("VisaUserControl.ascx"));
rpt1.Controls.Add(new LiteralControl("<BR>"));
}
}
protected void btnAddVisa_Click(object sender, EventArgs e)
{
ViewState["ControlCount"] = int.Parse(ViewState["ControlCount"].ToString()) + 1;
generateControls();
}
//Here is the problem when I read the values from control the loop comes out
private void saveData()
{
for (int i = 0; i < this.rpt1.Controls.Count; i++)
{
if (this.rpt1.Controls[i] is TextBox)
{
TextBox txtserial = (TextBox)this.rpt1.Controls[i];
string value = txtserial.Text;
}
}
}
protected void btnSaveVisa_Click(object sender, EventArgs e)
{
saveData();
}
Any ideas? Thanks in advance
public List<string> NoOfControls
{
get
{
return ViewState["NoOfControls"] == null ? new List<string>() : (List<string>)ViewState["NoOfControls"];
}
set
{
ViewState["NoOfControls"] = value;
}
}
protected override void LoadViewState(object savedState)
{
base.LoadViewState(savedState);
GenerateControls();
}
private void GenerateControls()
{
foreach (string i in NoOfControls)
{
var ctrl = (AddVisaUserControl)LoadControl(#"AddVisaUserControl.ascx");
ctrl.ID = i;
this.AddVisaPlaceHolder.Controls.Add(ctrl); // Add in placeholder
}
}
//Adding controls to Place Holder
protected void AddButton_Click(object sender, EventArgs e)
{
List<string> temp = null;
var uc = (AddVisaUserControl)this.LoadControl(#"AddVisaUserControl.ascx");
string id = Guid.NewGuid().ToString();
uc.ID = id;
temp = NoOfControls;
temp.Add(id);
NoOfControls = temp;
AddVisaPlaceHolder.Controls.Add(uc);
}
//Save
protected void Save_Click(object sender, EventArgs e)
{
foreach (var control in AddVisaPlaceHolder.Controls)
{
var usercontrol = control as AddVisaUserControl;
//you can access properties from usercontrol
//Implement save logic here
}
}

Export To Excel not Exporting Gridview Contents

I am trying to export gridview contents into Excel as given below, Excel is created but there is no content. but I am able to view the content in the webpage.
using System;
using System.IO;
using System.Reflection;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Xml;
using System.Data;
using System.Web.UI;
using System.Web;
namespace CustomReports.Reports
{
public partial class Reports : System.Web.UI.Page
{
DataTable ResultTable = new DataTable();
GridView ResultGrid = new GridView();
protected void Page_Load(object sender, EventArgs e)
{
}
public override void VerifyRenderingInServerForm(Control control)
{
/* Verifies that the control is rendered */
}
protected void Button1_Click(object sender, EventArgs e)
{
DataColumn col1 = new DataColumn("S.No");
DataColumn col2 = new DataColumn("Workflow Name");
DataColumn col3 = new DataColumn("Subject Name");
DataColumn col4 = new DataColumn("Subject ID");
col1.DataType = System.Type.GetType("System.Int32");
col2.DataType = System.Type.GetType("System.String");
col3.DataType = System.Type.GetType("System.String");
col4.DataType = System.Type.GetType("System.String");
ResultTable.Columns.Add(col1);
ResultTable.Columns.Add(col2);
ResultTable.Columns.Add(col3);
ResultTable.Columns.Add(col4);
CoreServiceSession client = new CoreServiceSession();
SessionAwareCoreServiceClient csClient = client.GetClient();
var readoption = new ReadOptions();
ProcessesFilterData filter = new ProcessesFilterData()
{
BaseColumns = ListBaseColumns.IdAndTitle,
ProcessType = ProcessType.Historical
};
int i = 1;
foreach (IdentifiableObjectData data in csClient.GetSystemWideList(filter))
{
var processHistory = data as ProcessHistoryData;
if (processHistory != null)
{
DataRow row = ResultTable.NewRow();
row[col1] = i;
row[col2] = processHistory.Title;
foreach (var subjectdetails in processHistory.Subjects)
{
row[col3] = subjectdetails.Title.ToString();
row[col4] = subjectdetails.IdRef.ToString();
}
ResultTable.Rows.Add(row);
}
i++;
}
//GridView ResultGrid = new GridView();
ResultGrid.DataSource = ResultTable;
ResultGrid.DataBind();
Panel1.Controls.Add(ResultGrid);
}
protected void Button2_Click(object sender, EventArgs e)
{
ExporttoExcel(ResultGrid, "Reports");
}
protected void ExporttoExcel(GridView objGridView, string FileName)
{
string attachment = "attachment; filename=" + FileName + ".xls";
HttpContext.Current.Response.ClearContent();
HttpContext.Current.Response.AddHeader("content-disposition", attachment);
HttpContext.Current.Response.ContentType = "application/ms-excel";
StringWriter objStringWriter = new StringWriter();
HtmlTextWriter objHtmlTextWriter = new HtmlTextWriter(objStringWriter);
objGridView.RenderControl(objHtmlTextWriter);
HttpContext.Current.Response.Write(objStringWriter.ToString());
HttpContext.Current.Response.End();
}
}
}
Excel is not imporing the content from the gridview, its blank
ASPX Code:
<%# Page Language="C#" AutoEventWireup="true" CodeBehind="Reports.aspx.cs" Inherits="CustomReports.Reports.Reports" EnableEventValidation="false" %>
<!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>Custom Report Page</title>
</head>
<body>
<form id="form1" runat="server">
<div>
<table id="table1" runat="server">
<tr>
<td>
<asp:Label ID="CustomReports1" runat="server" Text="Custom Reports"
Font-Bold="True"></asp:Label>
</td>
</tr>
<tr>
<td>
<asp:Label ID="SelectReportType2" runat="server" Text="Select Report Type"></asp:Label>
</td>
<td>
<asp:DropDownList ID="DDReportTypes" runat="server" Height="25px" Width="193px" onselectedindexchanged="DDReportTypes_SelectedIndexChanged" AutoPostBack = "true" ></asp:DropDownList>
</td>
</tr>
</table>
<table id="dynamictable" runat="server">
</table>
<table id="buttons">
<tr>
<td>
<asp:Button ID="Button1" runat="server" Text="Search" onclick="Button1_Click" />
</td>
<td>
<asp:Button ID="Button2" runat="server" Text="Export" onclick="Button2_Click" />
</td>
<td>
<asp:Button ID="Button3" runat="server" Text="GetValues" onclick="Button3_Click" />
</td>
</tr>
</table>
<asp:TextBox ID="TextBox0" runat="server" Height="28px" Width="355px"></asp:TextBox>
<asp:Panel ID="Panel1" runat="server">
<asp:GridView ID="ResultGrid" runat="server">
</asp:GridView>
</asp:Panel>
</div>
</form>
</body>
</html>
You don't need the form. Just render the grid:
ResultGrid.RenderControl(htw);
However, you need to add this code because usually the grid has to be in a form
public override void VerifyRenderingInServerForm(Control control)
{
}
Try export using this code...
Response.Clear();
Response.Buffer = true;
Response.AddHeader("content-disposition", "attachment;filename=fooreport.xls");
Response.Charset = "";
Response.ContentType = "application/ms-excel";
System.IO.StringWriter stringWrite = new System.IO.StringWriter();
System.Web.UI.HtmlTextWriter htmlWrite = new HtmlTextWriter(stringWrite);
lstEarningReport.RenderControl(htmlWrite);
Response.Write("<table border='1' > ");
Response.Write(stringWrite.ToString());
Response.Write("</table>");
Response.End();
This is an old question but ran into it when I had the same problem. EnableViewState was set to false on the gridview in my case. Setting it back to true fixed the issue. I was also databinding the gridview before exporting it, also removed that.

Categories

Resources