how to check the duplicate filename in asp:fileupload? - asp.net

i have an updatepanel and inside of it the contenttemplate is an asp:FileUpload..now when i will try to choose the file i want to check the filename in the database..i know my database part but how will i call the function in the server like for asp:TextBox i can use OnTextChanged something like that..but for asp:FileUpload is there anything by which i can check the filename and without clicking the button add?? my code
<asp:UpdatePanel runat="server" ID="fileupdatepanel">
<ContentTemplate>
<asp:FileUpload ID="tutorialupload" runat="server" AutoPostBack="true" OnLoad="filename_Changed" />
<asp:Label runat="server" ID="f1"></asp:Label>
</ContentTemplate>
</asp:UpdatePanel>
<asp:Button ID="addbttu" runat="server" Text="Add" OnClick="addtutorial_Click" />
my aspx.cs code
protected void filename_Changed(object sender, EventArgs e)
{
string con = " ";
con = ConfigurationManager.ConnectionStrings["ConnectionString"].ToString();
SqlConnection objsqlconn = new SqlConnection(con);
objsqlconn.Open();
string tuname = tutorialupload.PostedFile.FileName;
tuname = tuname.Substring(0, tuname.LastIndexOf("."));
SqlCommand objcmd = new SqlCommand("Select tutorialid from tutorialtable where tutorialname='" + tuname + "'", objsqlconn);
SqlDataReader grpIDreader = objcmd.ExecuteReader();
grpIDreader.Read();
if (grpIDreader.HasRows)
{
f1.Text = "Duplicate filename.Sorry.";
}
else
{
f1.Text = "";
}
objsqlconn.Close();
}
now when i will choose the file..i want to call this function filename_Changed() and it will give me the result whether the filename is present or not..so i want to do it without clicking my the add button??

You should use the has file property, when true do you DB check, something like this
protected void UploadButton_Click(object sender, EventArgs e)
{
if (FileUpload1.HasFile)
// Before attempting to save the file, do something
else
// Notify the user that a file was not uploaded.
UploadStatusLabel.Text = "You did not specify a file to upload.";
}

Here is how you can detect the change in the selected file name using JavaScript through the FileUpload onChange event.
ASPX Page: Make sure to set EnablePageMethods = true in the ScriptManager object.
<asp:ScriptManager ID="ScriptManager1" runat="server" EnablePageMethods="true"></asp:ScriptManager>
<asp:UpdatePanel runat="server" ID="fileupdatepanel">
<ContentTemplate>
<asp:FileUpload ID="tutorialupload" runat="server" OnChange="CheckFileName(this)" />
<asp:Label runat="server" ID="f1"></asp:Label>
</ContentTemplate>
</asp:UpdatePanel>
<asp:Button ID="addbttu" runat="server" Text="Add" OnClick="addtutorial_Click" />
JavaScript:
function CheckFileName(oFile)
{
PageMethods.FileNameChecker(oFile.value, OnSucceeded);
}
function OnSucceeded(result, userContext, methodName)
{
lbl = document.getElementById('<%=f1.ClientID %>');
if (methodName == "FileNameChecker")
{
if (result == true)
{
lbl.innerHTML = 'Duplicate filename.Sorry.';
lbl.style.color = "red";
}
else
{
lbl.innerHTML = '';
}
}
}
C# Code-Behind: You can call a WebMethod to check if the new selected filename exists in the DB:
You need to reference the following:
using System.Web.Services;
Then add the following method and make sure you put [WebMethod] before method declaration:
[WebMethod]
public static bool FileNameChecker(string newFileName)
{
string con = " ";
con = ConfigurationManager.ConnectionStrings["ConnectionString"].ToString();
SqlConnection objsqlconn = new SqlConnection(con);
objsqlconn.Open();
string x = newFileName.Substring(0,newFileName.LastIndexOf("\\"));
string tuname = newFileName.Substring(newFileName.LastIndexOf("\\") + 1, newFileName.Length - x.Length - 1);
tuname = tuname.Substring(0, tuname.LastIndexOf("."));
SqlCommand objcmd = new SqlCommand("Select tutorialid from tutorialtable where tutorialname='" + tuname + "'", objsqlconn);
SqlDataReader grpIDreader = objcmd.ExecuteReader();
grpIDreader.Read();
bool found = false;
if (grpIDreader.HasRows)
found = true;
objsqlconn.Close();
return found;
}

Related

bind image from database to datalist

I am binding image to datalist.
My imagename is in database, i am taking it and wants to bind it to datalist.
I have tried following:
<asp:DataList ID="dlImages" runat="server">
<ItemTemplate>
<asp:ImageButton ID="ImageButton1" Height="200px" Width="200px"
ImageUrl='<%# Bind ("PageName","D:\Sagar\Kinston\WebSite\ScreenMasterImages\{0}") %>' runat="server" />
</ItemTemplate>
</asp:DataList>
on pageload i have bounded it as:
ds = gc.GetDataToListBinder("select DISTINCT PageOrderID,PageName from ScreenMaster order by PageOrderID")
dlImages.DataSource = ds.Tables(0)
dlImages.DataBind()
In above code ds is my dataset and gc.GetDataToListBinder(query) returns dataset.
But images are not getting displayed.
What can be the mistake?
EDIT1:
<asp:ImageButton ID="ImageButton1" Height="200px" Width="200px" ImageUrl='<%#Server.HtmlDecode(Eval("PageName","D:\Sagar\Kinston\WebSite\ScreenMasterImages\{0}.jpg")) %>' runat="server" />
Take a minute and read this:
http://www.codeproject.com/Articles/142013/There-is-something-about-Paths-for-Asp-net-beginne
I think this will help you alot.
EDIT:
For the space problem, take a look:
Why does HttpUtility.UrlEncode(HttpUtility.UrlDecode("%20")) return + instead of %20?
Basically:
ImageUrl='<%# Server.HtmlDecode(Bind("MyImage")) %>'
But i recommend that you store your image name without space in db.
EDIT2:
ImageUrl='<%# Eval("MyImage") %>'
ImageUrl='<%# Server.HtmlDecode(Eval("MyImage")) %>'
<asp:DataList ID="DataList1" runat="server" RepeatColumns="3"
RepeatDirection="Horizontal" CellPadding="2"
CellSpacing="2"
UseAccessibleHeader="True" >
<ItemTemplate>
<asp:ImageButton Width="120" Height="120" ID="Image1" ImageUrl='<%# Eval("Imgpath", "") %>' runat="server" />
</asp:Datalist>
.CS
SqlConnection con;
SqlCommand cmd;
string strCon = "Connection String";
SqlDataAdapter da;
protected void AlldataImg()
{
DataTable dt = new DataTable();
string strQuery = "select code,imgpath from SA_Stock order by Code";
cmd = new SqlCommand(strQuery);
con = new SqlConnection(strCon);
da = new SqlDataAdapter();
cmd.CommandType = CommandType.Text;
cmd.Connection = con;
try
{
con.Open();
da.SelectCommand = cmd;
da.Fill(dt);
DataList1.DataSource = dt;
DataList1.DataBind();
}
catch (Exception ex)
{
Response.Write(ex.Message);
}
finally
{
con.Close();
da.Dispose();
con.Dispose();
}
}
protected void Page_Load(object sender, EventArgs e)
{
AlldataImg();
}
Put Image Path in database too so that image will appear..
protected void DataListPosts_ItemDataBound(object sender, DataListItemEventArgs e)
{
try
{
if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem)
{
DataRowView dr = (DataRowView)e.Item.DataItem;
Image ImageData = (Image)e.Item.FindControl("ImageData");
if (dr.Row[4].ToString() != "NA")
{
ImageData.Visible = true;
ImageData.ImageUrl = #"ImgPost/" + dr.Row["ImgPath"].ToString();
}
else
ImageData.Visible = false;
}
}
catch (Exception)
{ }
}
its a old topic but i think it can be usefull for anyone
firstly get your data from string
string sqlget = "select Photo from Promoter";
and get it to database dsget
then do that
dsget.Tables[0].Columns.Add("Photopath", typeof(string));
for (int i = 0; i < dsget.Tables[0].Rows.Count; i++)
{
if (dsget.Tables[0].Rows[i]["Photo"].ToString() != null && dsget.Tables[0].Rows[i]["Photo"].ToString() != "")
{
var data = (Byte[])(dsget.Tables[0].Rows[i]["Photo"]);
var stream = new MemoryStream(data);
System.IO.BinaryReader br = new System.IO.BinaryReader(stream);
FileBytes = br.ReadBytes((Int32)stream.Length);
string base64String = Convert.ToBase64String(FileBytes, 0, FileBytes.Length);
dsget.Tables[0].Rows[i]["Photopath"] = "data:image/png;base64," + base64String;
}
}
DataList1.DataSource = dsget.Tables[0];
DataList1.DataBind();
in asp file write the following thing

How to generate a print preview in a single button click in report viewer?

This is my aspx page..................
<asp:Panel ID="UpdatePanel1" runat="server" Visible="false" >
<rsweb:ReportViewer ID="ReportingForPrintingReportViewer" runat="server"
Width="100%" Height="100%" Font-Names="Verdana" Font-Size="8pt"
InteractiveDeviceInfos="(Collection)" WaitMessageFont-Names="Verdana"
WaitMessageFont-Size="14pt">
<LocalReport ReportPath="Report.rdlc">
<DataSources>
<rsweb:ReportDataSource DataSourceId="ObjectDataSource2" Name="DataSet1" />
</DataSources>
</LocalReport>
</rsweb:ReportViewer>
<asp:ObjectDataSource ID="ObjectDataSource2" runat="server"
SelectMethod="GetData" TypeName="DataSet1TableAdapters.tblTotalFeeTableAdapter">
</asp:ObjectDataSource>
</asp:Panel>
<asp:Button ID="btnSubmit" runat="server" Text="Submit" Width="150px"
onclick="btnSubmit_Click" />
<asp:Button ID="btnReset" runat="server" Text="Reset" Width="150px" />
<asp:Button ID="btnCreateBill" runat="server" Text="CreateBill" Width="150px"
onclick="btnCreateBill_Click"/>
<asp:PopupControlExtender ID="btnCreateBill_PopupControlExtender" OffsetX="-1100" OffsetY="115"
runat="server" DynamicServicePath="" Enabled="True" ExtenderControlID=""
TargetControlID="btnCreateBill" PopupControlID="UpdatePanel1">
</asp:PopupControlExtender>
This is my cs page
protected void btnCreateBill_Click(object sender, EventArgs e)
{
DisplayReport();
UpdatePanel1.Visible = true;
}
private DataTable TotalInfoData()
{
try
{
//DataClassesDataContext db = null;
//db = new DataClassesDataContext();
//var s = from p in db.tblTotalFeess
// where p.Class == ClassDropDownList.SelectedItem.Value && p.StudentID == Convert.ToInt32(StudentNameDropDownList.SelectedValue)
// select p;
//DataTable dt = new DataTable();
//SQLHelper sqhlpr = new SQLHelper();
//sqhlpr.SqlText = "select * from tblTotalFee where Class='" + ClassDropDownList.SelectedItem.Value + "'" + "and StudentID='" + StudentNameDropDownList.SelectedValue + "'";
//DataTable dt = sqhlpr.getDataTable(false);
//return dt;
try
{
// Open Sql Connection
SqlConnection SqlCon = new SqlConnection(#"Data Source=PRATIKPC;Initial Catalog=dbbilling2.0;Integrated Security=True");
SqlCon.Open();
// Create a Command
SqlCommand SqlComm = new SqlCommand();
SqlComm.Connection = SqlCon;
SqlComm.CommandType = CommandType.Text;
SqlComm.CommandText = "select * from tblTotalFee where Class='" + ClassDropDownList.SelectedItem.Value + "'" + "and StudentID='" + StudentNameDropDownList.SelectedValue + "'";
// Create instance of Northwind DataSetXSD
DataSet1.tblTotalFeeDataTable dtbl = new DataSet1.tblTotalFeeDataTable();
// Set a Data Commands
SqlDataAdapter SqlDa = new SqlDataAdapter(SqlComm);
SqlDa.Fill(dtbl); // Fill Data in NorthwindDataSet Object.
return dtbl;
}
catch (Exception ex)
{
throw new Exception(ex.Message);
}
}
catch (Exception ex)
{
throw new Exception(ex.Message);
}
}
private void DisplayReport()
{
try
{
// Clear the Data Source
ReportingForPrintingReportViewer.LocalReport.DataSources.Clear();
// Set a DataSource to the report
// First Parameter - Report DataSet Name
// Second Parameter - DataSource Object i.e DataTable
ReportingForPrintingReportViewer.LocalReport.DataSources.Add(new ReportDataSource("DataSet1", TotalInfoData()));
// OR Set Report Path
ReportingForPrintingReportViewer.LocalReport.ReportPath = HttpContext.Current.Server.MapPath("~/Report.rdlc");
// Refresh and Display Report
ReportingForPrintingReportViewer.LocalReport.Refresh();
}
catch (Exception ex)
{
throw new Exception(ex.Message);
}
}
I have to click btnCreateBill twice to generate report viewer. Why? And how can I generate report viewer in a single click of a button?
Are you call your Get Data method(Your Data Source load method
) in Inside of !ispostback ?
for look this
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
GetData()// Your Data Source load method
}
}
This is Aspx file........................
<%# Page Title="" Language="C#" MasterPageFile="~/Site.Master" AutoEventWireup="true"
CodeBehind="AccountReportParameter.aspx.cs" Inherits="TexERP.ReportSSRS.AccountReportParameter" %>
<%# Register Assembly="Microsoft.ReportViewer.WebForms, Version=10.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a"
Namespace="Microsoft.Reporting.WebForms" TagPrefix="rsweb" %>
<asp:Content ID="Content1" ContentPlaceHolderID="HeadContent" runat="server">
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="MainContent" runat="server"> <asp:UpdatePanel ID="updpnlLiteral" runat="server">
<ContentTemplate>
<asp:Panel ID="pnlAddRecord" runat="server" BackColor="White" Height="150px" Width="600px"
Visible="true">
<td align="right" colspan="4">
<asp:Button ID="btnSubmit" runat="server" Text="Show Report" OnClick="btnSubmit_Click"
ValidationGroup="FinalSave" />
<asp:Button ID="btnCancel" runat="server" Text="Reset" UseSubmitBehavior="false"
OnClick="btnCancel_Click" />
</asp:Panel>
<rsweb:ReportViewer ID="rptvwMain" runat="server" Width="907px" Height="850px" Font-Names="Verdana"
Font-Size="8pt" ProcessingMode="Remote" ShowCredentialPrompts="false" InteractiveDeviceInfos="(Collection)"
ShowZoomControl="true">
</rsweb:ReportViewer>
</ContentTemplate>
</asp:UpdatePanel>
</asp:Content>
This is cs file...........
using System;
using System.Collections.Generic;
using System.Data;
using System.Net;
using BusinessAccessLevel;
using BusinessAccessLevel.Masters;
using Microsoft.Reporting.WebForms;
namespace TexERP.ReportCrystal
{
public partial class AccountReportParameter : System.Web.UI.Page
{
AccountReportBAL objAccountReportBAL;
clsSession objSession;
string pstrType;
protected void Page_Load(object sender, EventArgs e)
{
objAccountReportBAL = new AccountReportBAL();
objSession = new clsSession();
pstrType = Request.QueryString["Type"];
if (Session["objSession"] != null)
{
objSession = Session["objSession"] as clsSession;
}
objAccountReportBAL = new AccountReportBAL();
if (!IsPostBack)
{
RadDtpFromDate.SelectedDate = Convert.ToDateTime(objSession.FyFromDate);
RadDtpToDate.SelectedDate = Convert.ToDateTime(objSession.FyToDate);
}
rptvwMain.LocalReport.Refresh();
}
protected void btnSubmit_Click(object sender, EventArgs e)
{
string pstrType;
pstrType = Request.QueryString["Type"];
LoadReport();
}
public class CustomReportCredentials : Microsoft.Reporting.WebForms.IReportServerCredentials
{
// local variable for network credential.
private string _UserName;
private string _PassWord;
private string _DomainName;
public CustomReportCredentials(string UserName, string PassWord, string DomainName)
{
_UserName = UserName;
_PassWord = PassWord;
_DomainName = DomainName;
}
public System.Security.Principal.WindowsIdentity ImpersonationUser
{
get
{
return null; // not use ImpersonationUser
}
}
public System.Net.ICredentials NetworkCredentials
{
get
{
// use NetworkCredentials
return new NetworkCredential(_UserName, _PassWord, _DomainName);
}
}
public bool GetFormsCredentials(out Cookie authCookie, out string user, out string password, out string authority)
{
// not use FormsCredentials unless you have implements a custom autentication.
authCookie = null;
user = password = authority = null;
return false;
}
}
void LoadReport()
{
string strCompanyName = objSession.SelCompanyName;
string strHeading = "";
string strBranchName = objSession.SelBranchName;
rptvwMain.ProcessingMode = ProcessingMode.Remote;
rptvwMain.ServerReport.ReportServerCredentials = new CustomReportCredentials(AppConfig.ReportServerUserName, AppConfig.ReportServerPassword, AppConfig.ReportServerDomain);
string strReportServerUrl = AppConfig.ReportServerUrl + AppConfig.ReportServerFolder;
rptvwMain.ServerReport.ReportServerUrl = new Uri(strReportServerUrl);
List<ReportParameter> parameters = new List<ReportParameter>();
if(pstrType == "GL")
{
strHeading = "General Ledger";
rptvwMain.ServerReport.ReportPath = "/Account/AccountGeneralLedger";
}
parameters.Add(new ReportParameter("FyId", Convert.ToInt16(objSession.FyId).ToString()));
parameters.Add(new ReportParameter("AccountGroupId", cmbAccountGroup.SelectedValue));
parameters.Add(new ReportParameter("LedgerId", cmbLedgerId.SelectedValue));
parameters.Add(new ReportParameter("BranchId", Convert.ToInt64(objSession.BranchId).ToString()));
parameters.Add(new ReportParameter("StDate", Convert.ToDateTime(RadDtpFromDate.SelectedDate).ToString()));
parameters.Add(new ReportParameter("EnDate", Convert.ToDateTime(RadDtpToDate.SelectedDate).ToString()));
parameters.Add(new ReportParameter("CompanyName", strCompanyName.ToString()));
parameters.Add(new ReportParameter("BranchName", strBranchName.ToString()));
parameters.Add(new ReportParameter("Heading",strHeading.ToString()));
rptvwMain.ServerReport.SetParameters(parameters);
rptvwMain.ServerReport.SetDataSourceCredentials(new[] { new DataSourceCredentials() { Name =AppConfig.ReportServerDataSource , UserId = AppConfig.ReportServerDSUserName, Password = AppConfig.ReportServerDSPassword } });
rptvwMain.ShowZoomControl = true;
rptvwMain.ServerReport.Refresh();
}
}
}
Try this code as reference code................

Reload GridView or Repeater on AjaxFileUpload UploadComplete Event in ASP.NET

Hi is there anyway to update (Gridview or Repeater data) after AjaxFileUpload UploadComplete Event. What I want to do is upload multiple picture using AjaxFileUpload and once the files are uploaded it should display those pictures into a GridView or Repeater control.
I could not do this unless a button click event is fired.
Any ideas???
Put hidden button onto a form and attach this function to OnClientUploadComplete event handler of extender
<asp:Button runat="server" ID="HiddenButton" OnClick="RefreshGridView" style="display:none;" />
function uploadComplete(sender, args) {
for (var index = 0; index < sender._filesInQueue.length; ++index) {
if (!sender._filesInQueue[index]._isUploaded) {
return;
}
}
__doPostBack("<%= HiddenButton.UniqueID %>", "");
})
then, refresh your GridView on this button's click.
This code checks for the file that's uploaded, creates an email with the file information, emails the person the file was intended for with a link. It also stores all the info into a database. On the upload page is a gridview that lists all the files that have been uploaded. It updates after the files is loaded. I think you can get what you need out of it.
Partial Class upload_Default
Inherits System.Web.UI.Page
Protected Sub UploadButton2_Click(sender As Object, e As EventArgs)
Dim fileGuid As String
fileGuid = Guid.NewGuid.ToString
If AsyncFileUpload1.HasFile Then
If AsyncFileUpload1.FileContent.Length < 20971500 Then
Try
Dim fileSizeB As Integer = AsyncFileUpload1.PostedFile.ContentLength
Dim fileSize = fileSizeB / 1024
Dim filename As String = Path.GetFileName(AsyncFileUpload1.FileName)
Dim fileNameTwo As String = Trim(fileGuid) + Trim(filename)
Dim ExistPdfFilenamOPO As String
ExistPdfFilenamOPO = Server.MapPath("~/uploads/files/") & filename
If File.Exists(ExistPdfFilenamOPO) Then
Label2.Text = "File is already there"
Else
Dim saveDir As String = "\Uploads\files\"
Dim appPath As String = Request.PhysicalApplicationPath
Dim savePath As String = appPath + saveDir + _
Server.HtmlEncode(AsyncFileUpload1.FileName)
AsyncFileUpload1.SaveAs(savePath)
UploadStatusLabel2.Text = "Upload status: File uploaded."
Label2.Text = ""
' Email
Dim sr As New StreamReader(appPath & "EmailTemplates/FileUpload.htm")
Dim FName As String = TextBoxFName.Text
Dim LName As String = TextBoxLName.Text
Dim Email As String = TextBoxEmail.Text
Dim fullPath As String
fullPath = "https://website.com/uploads/default.aspx?fileGuid=" + fileGuid
Dim message As New MailMessage()
message.IsBodyHtml = True
message.From = New MailAddress("Your email")
message.[To].Add(New MailAddress(Email))
message.Subject = "The file you requested from SRTR"
message.Body = sr.ReadToEnd()
sr.Close()
message.Body = message.Body.Replace("<%FName%>", FName)
message.Body = message.Body.Replace("<%LName%>", LName)
message.Body = message.Body.Replace("<%Email%>", Email)
message.Body = message.Body.Replace("<%FileName%>", filename)
message.Body = message.Body.Replace("<%VerificationUrl%>", fullPath)
Dim client As New SmtpClient()
client.Send(message)
'Insert in to t_UploadFiles
Dim datenow As Date = System.DateTime.Now()
Dim ExDate As Date = datenow.AddDays(15)
Dim Downloaded As Boolean = False
Dim connectionString As String = ConfigurationManager.ConnectionStrings("ConnectionString").ConnectionString
Dim updateSql As String = "INSERT t_UploadFiles (FileGuid, FileName, FileSize, FName, LName, Email, UploadDate, ExDate, Downloaded) SELECT #FileGuid, #FileName, #FileSize, #FName, #LName, #Email, #UploadDate, #ExDate, #Downloaded"
Using myConnection As New SqlConnection(connectionString)
myConnection.Open()
Dim myCommand As New SqlCommand(updateSql, myConnection)
myCommand.Parameters.AddWithValue("#FileGuid", fileGuid.Trim())
myCommand.Parameters.AddWithValue("#FileName", filename.Trim())
myCommand.Parameters.AddWithValue("#FileSize", fileSize)
myCommand.Parameters.AddWithValue("#FName", FName.Trim())
myCommand.Parameters.AddWithValue("#LName", LName.Trim())
myCommand.Parameters.AddWithValue("#Email", Email)
myCommand.Parameters.AddWithValue("#UploadDate", datenow)
myCommand.Parameters.AddWithValue("#ExDate", ExDate)
myCommand.Parameters.AddWithValue("#Downloaded", Downloaded)
myCommand.ExecuteNonQuery()
myConnection.Close()
End Using
articleListXX.DataBind()
End If
Catch ex As Exception
UploadStatusLabel2.Text = "Upload status: The file could not be uploaded.<br/>The following error occured: " + ex.Message
End Try
Else
UploadStatusLabel2.Text = "File is too large."
End If
Else
UploadStatusLabel2.Text = "You did not specify a file to upload."
End If
End Sub
End Class
Ok guys thanks for your contribution and sorry for making my query a bit unclear. I finally figured it out but only because of your ideas. Here is my code. The same applies to gridview. The main purpose is to use AjaxFileUpload control to upload pictures and on OnUploadComplete="AjaxFileUpload1_UploadComplete" event call the method for creating thumbnail image. Once thumbnails are created the method populatePic() is call to populate thumbnail images into a repeater control with the help of javascript _doPostBack() method without the needs of firing a button by the user.
<script type="text/javascript">
function showUploadedPic()
{
__doPostBack('btnAdd', null);
}
</script>
<cc1:AjaxFileUpload ID="AjaxFileUpload1" runat="server" OnUploadComplete="AjaxFileUpload1_UploadComplete" ThrobberID="myThrobber" MaximumNumberOfFiles="10" AllowedFileTypes="jpg,jpeg" OnClientUploadComplete="showUploadedPic" />
<asp:UpdatePanel ID="UpdatePanel1" runat="server">
<asp:Repeater ID="Repeater1" runat="server">
<ItemTemplate>
<asp:Image ID="Image1" runat="server" ImageUrl="<%# Container.DataItem %>" height="100"/>
</ItemTemplate>
</asp:Repeater>
</ContentTemplate>
<Triggers>
<asp:AsyncPostBackTrigger ControlID="btnAdd" EventName="Click" />
</Triggers>
</asp:UpdatePanel>
Code Behind
protected void btnAdd_Click(object sender, EventArgs e)
{
populatePic();
}
protected void AjaxFileUpload1_UploadComplete(object sender, AjaxControlToolkit.AjaxFileUploadEventArgs e)
{
string filePath = Server.MapPath("~/files/") + e.FileName;
AjaxFileUpload1.SaveAs(filePath);
createThumbnail();
}
Below code is tested and works.
<asp:Button runat="server" ID="HiddenButtonFileUpload"
OnClick="RefreshGridView" style="display:none;" />
<ajax:AjaxFileUpload ID="AjaxFileUpload11" runat="server"
MaximumNumberOfFiles="3" AllowedFileTypes="txt,xls,xlsx,doc,docx,pdf"
Width="400px"
OnUploadComplete="OnUploadComplete"
OnClientUploadStart="UploadStart" OnClientUploadCompleteAll="UploadComplete"
ClearFileListAfterUpload="true" />
function UploadComplete() {
unblock();
__doPostBack("<%= HiddenButtonFileUpload.UniqueID %>", "");
}
Code Behind :
protected void RefreshGridView(object sender, EventArgs e)
{
BindForm(); // refresh your gridview
}

Displaying image on a separate page

I have a image datatype which on click of a linkbutton needs to be displayed on a seperate page
aspx page
detail view:
<asp:TemplateField HeaderText="Evidence (if any)">
<ItemTemplate>
<asp:LinkButton ID="lbEvidence" runat="server"
Text='<%# DataBinder.Eval(Container.DataItem, "Evidence").ToString() == String.Empty ? "None" : DataBinder.Eval(Container.DataItem, "Evidence")%>'
CommandName="Select" CommandArgument = '<%# DataBinder.Eval(Container.DataItem, "Complaint_Id") %>'> </asp:LinkButton>
</ItemTemplate>
</asp:TemplateField>
ImageHandler.ashx
<%# WebHandler Language="C#" Class="FMMadminModule.imageHandler" %>
using System;
using System.Web;
using System.Data;
using System.Web.SessionState;
namespace FMMadminModule
{
public class imageHandler : IHttpHandler, IReadOnlySessionState
{
DataTable dt;
int key;
byte[] imageOut;
public void ProcessRequest(HttpContext context)
{
HttpResponse response = context.Response;
HttpRequest request = context.Request;
context.Response.ContentType = "image/jpeg";
response.BufferOutput = false;
// get the key, the index into the DataTable
key = Convert.ToInt32(request.QueryString["Complaint_ID"]);
// Prepare the datatable to hold the SNo key and the jpeg image, which will be written out
dt = new DataTable();
dt = (DataTable)context.Session["dt"];
if (!dt.Rows[key]["Evidence"].Equals(null))
{
imageOut = (byte[])dt.Rows[key]["Evidence"];
response.OutputStream.Write(imageOut, 0, imageOut.Length);
}
}
public bool IsReusable
{
get
{
return false;
}
}
}
}
How would I display the image on a separate page?
This is how aspx.cs looks like
protected void dvResolveComplaint_ItemCommand(object sender, DetailsViewCommandEventArgs e)
{
if (e.CommandName == "Select")
{
DetailsViewRow row = dvResolveComplaint.Rows[5];
//String RowId = (e.NewSelectedIndex).ToString();
Type csType = this.GetType();
String strScript = "<script> ";
strScript += #"var newWindow = window.open('imageHandler.ashx?Complaint_ID=" + e.CommandArgument + #"', 'Evidence', ' height=450, center:yes, width=600, status=no, resizable= yes, menubar=no, toolbar=no, location=yes, scrollbars=no, status=no')";
strScript += "</script>";
ClientScript.RegisterClientScriptBlock(csType, "ViewEvidence", strScript);
dvResolveComplaint.Attributes.Add("OnClick", strScript);
}
}
this is way overcomplicated. You don't need the linkbutton at all, just write an anchor-wrapped image in your item template and call it a day, e.g.:
<img src='url_to_your_handler' alt='complaint image' />

asp.net how to add TemplateField programmatically for about 10 dropdownlist

This is my third time asking this question. I am not getting good answers regarding this. I wish I could get some help but I will keep asking this question because its a good question and SO experts should not ignore this...
So I have about 10 dropdownlist controls that I add manually in the DetailsView control manually like follows. I should be able to add this programmatically. Please help and do not ignore...
<asp:DetailsView ID="dvProfile" runat="server"
AutoGenerateRows="False" DataKeyNames="memberid" DataSourceID="SqlDataSource1"
OnPreRender = "_onprerender"
Height="50px" onm="" Width="125px">
<Fields>
<asp:TemplateField HeaderText="Your Gender">
<EditItemTemplate>
<asp:DropDownList ID="ddlGender" runat="server"
DataSourceid="ddlDAGender"
DataTextField="Gender" DataValueField="GenderID"
SelectedValue='<%#Bind("GenderID") %>'
>
</asp:DropDownList>
</EditItemTemplate>
<ItemTemplate >
<asp:Label Runat="server" Text='<%# Bind("Gender") %>' ID="lblGender"></asp:Label>
</ItemTemplate>
<asp:CommandField ShowEditButton="True" ShowInsertButton="True" />
</Fields>
</asp:DetailsView>
=======================================================
Added on 5/3/09
This is what I have so far and I still can not add the drop down list programmatically.
private void PopulateItemTemplate(string luControl)
{
SqlDataSource ds = new SqlDataSource();
ds = (SqlDataSource)FindControl("ddlDAGender");
DataView dvw = new DataView();
DataSourceSelectArguments args = new DataSourceSelectArguments();
dvw = (DataView)ds.Select(args);
DataTable dt = dvw.ToTable();
DetailsView dv = (DetailsView)LoginView2.FindControl("dvProfile");
TemplateField tf = new TemplateField();
tf.HeaderText = "Your Gender";
tf.ItemTemplate = new ProfileItemTemplate("Gender", ListItemType.Item);
tf.EditItemTemplate = new ProfileItemTemplate("Gender", ListItemType.EditItem);
dv.Fields.Add(tf);
}
public class ProfileItemTemplate : ITemplate
{
private string ctlName;
ListItemType _lit;
private string _strDDLName;
private string _strDVField;
private string _strDTField;
private string _strSelectedID;
private DataTable _dt;
public ProfileItemTemplate(string strDDLName,
string strDVField,
string strDTField,
DataTable dt
)
{
_dt = dt;
_strDDLName = strDDLName;
_strDVField = strDVField;
_strDTField = strDTField;
}
public ProfileItemTemplate(string strDDLName,
string strDVField,
string strDTField,
string strSelectedID,
DataTable dt
)
{
_dt = dt;
_strDDLName = strDDLName;
_strDVField = strDVField;
_strDTField = strDTField;
_strSelectedID = strSelectedID;
}
public ProfileItemTemplate(string ControlName, ListItemType lit)
{
ctlName = ControlName;
_lit = lit;
}
public void InstantiateIn(Control container)
{
switch(_lit)
{
case ListItemType.Item :
Label lbl = new Label();
lbl.DataBinding += new EventHandler(this.ddl_DataBinding_item);
container.Controls.Add(lbl);
break;
case ListItemType.EditItem :
DropDownList ddl = new DropDownList();
ddl.DataBinding += new EventHandler(this.lbl_DataBinding);
container.Controls.Add(ddl);
break;
}
}
private void ddl_DataBinding_item(object sender, EventArgs e)
{
DropDownList ddl = (DropDownList)sender;
ddl.ID = _strDDLName;
ddl.DataSource = _dt;
ddl.DataValueField = _strDVField;
ddl.DataTextField = _strDVField;
}
private void lbl_DataBinding(object sender, EventArgs e)
{
Label lbl = (Label)sender;
lbl.ID = "lblGender";
DropDownList ddl = (DropDownList)sender;
ddl.ID = _strDDLName;
ddl.DataSource = _dt;
ddl.DataValueField = _strDVField;
ddl.DataTextField = _strDTField;
for (int i = 0; i < _dt.Rows.Count; i++)
{
if (_strSelectedID == _dt.Rows[i][_strDVField].ToString())
{
ddl.SelectedIndex = i;
}
}
lbl.Text = ddl.SelectedValue;
}
}
I found this article http://aspalliance.com/1125 about progrmatically creating template field. I hope this can be helpful to solve this problem.
What have you tried? What problem are you having? If you haven't answered these questions before, then it's no surprise that you haven't received a good answer.
Obviously, you have to locate the TemplateFields for which you want to add dropdowns, and you have to set their EditItemTemplate property to an instance of a class that implements ITemplate. That instance will have it's InstantiateIn method called to add controls to a parent control. In this case, this is where you would configure and add your DropDownList.
If this description is not adequate, then you'll have to say in what way it's not adequate, so that I or someone else can answer.

Resources