FileUpload upload codebehind. - c#

How can i upload with FileUpload codebehind only? My controls are made codebehind because i have Dropdown_SelectedIndexChanged and need to generate various numbers of controls. I can list the controls fine and attach file and text to txtbox with:
private void SetChildrenCountControls(int total)
{
for (int i = 0; i < total; i++)
{
var tbBirthDate = new TextBox();
tbBirthDate.ID = "tbBirthDate_" + (i + 1);
tbBirthDate.CssClass = "tbSister_input";
tbBirthDate.EnableViewState = true;
FileUpload upload = new FileUpload();
upload.ID = "imgUpload_" + (i + 1);
upload.CssClass = "tbSister_upload";
upload.EnableViewState = true;
ChildrenCountTextPanel.Controls.Add(tbBirthDate);
ChildrenCountTextPanel.Controls.Add(upload);
}
}
And can get the enterede text in the txtbox with:
protected void lbFamilySave_Click(object sender, EventArgs e)
{
var countSisters = ChildrenCountTextPanel.Controls.OfType<TextBox>();
string sisterBirth = string.Empty;
foreach (var sister in countSisters)
{
if (sister.ID.Contains("tbBirthDate_"))
sisterBirth = sister.Text;
}
}
How can i get the file from the FileUpload controls? Cant seem to do above with FileUpload.

In the click event below you are getting TextBoxes and not FileUpload Control
btn_protected void lbFamilySave_Click(object sender, EventArgs e)
{
var countSisters = ChildrenCountTextPanel.Controls.OfType<TextBox>();
A file upload control is of this type System.Web.UI.WebControls.FileUpload
So please get the FileUpload control then do the following:
if (myFileUpload.HasFile)
{
string savePath = #"C:\Temp\" + myFileUpload.FileName;
myFileUpload.SaveAs(savePath);
}

Got it working with this, thought i had tryed that. Apparently not good enough :)
var countUploads = ChildrenCountTextPanel.Controls.OfType<FileUpload>();
FileUpload FileUl = new FileUpload();
foreach (var ul in countUploads)
{
if(ul.ID.Contains("imgUpload_"))
{
FileUl = ul;
}
}
if (FileUl.HasFile)
{
ConvertAndSave(FileUl)
}

Related

Recreating many dynamic controls in ASP NET (individually actions)

I have problem with ASP.NET and dynamic controls. I have three ASCX. One of them creates two textboxes and some labels. The second containing control created if first ASCX (two textboxes and some labels). In addiction, second control also have link button named “Add Next” which on click event adding another control (two textboxes and some labels). The third ASCX control contains many the second ASCX (amount depend on SQL result). I made simple image to clarify:
The orange box contains many controls. The red box adding many black boxes on click “ADD NEXT”.
For now I use session variable to save state during recreate. For one “red box” it is working, but if I add more “red boxes”, clicking every “ADD NEXT” adding new control with textboxes and labels to every “red box” instead of in this where was clicked button “ADD NEXT”. I suppose why it is happening. Because every “red box” refers to the same Session variable, but I don’t know how to fix it. I was trying during OnClick event passing unique ID and setting this ID as session variable name, but it wasn’t working as I expected.
Could you tell me, how to manage it? How looks the best way to recreate controls, how I can manage controls individually? If something is not clear, I will clarify. Always I was finding answers in stackoverflow, but this problem has outgrow me.
Best wishes.
(Sorry for my English, it doesn’t my native language)
My code.
Code for creating textboxes and some labels (Calculator.cs):
public string FLong
{
get
{
object o = ViewState["FLong"];
if (o == null)
return String.Empty;
return (string)o;
}
set { ViewState["FLong"] = value; }
}
public string FWide
{
get
{
object o = ViewState["FWide"];
if (o == null)
return String.Empty;
return (string)o;
}
set
{
ViewState["FWide"] = value;
}
}
protected override void OnInit(EventArgs e)
{
base.OnInit(e);
CreateControlHierarchy();
ClearChildViewState();
}
protected virtual void CreateControlHierarchy()
{
Literal row = new Literal();
row.Text = "<div class='row surface'>";
Controls.Add(row);
//Add new TextBox;
Literal col = new Literal();
col.Text = "<div class='col-xs-4'>";
Controls.Add(col);
TextBox fLong = new TextBox();
fLong.ID = "fLong";
fLong.CssClass = "form-control";
//fLong.TextChanged += new EventHandler(Calculate_TextChanged);
//fLong.AutoPostBack = true;
fLong.Text = FLong;
Controls.Add(fLong);
Literal textLong = new Literal();
textLong.Text = "<span>ft. long x</span>";
Controls.Add(textLong);
RegularExpressionValidator flongValidate = new RegularExpressionValidator();
flongValidate.ControlToValidate = "fLong";
flongValidate.ErrorMessage = "Only Numbers allowed";
flongValidate.ValidationExpression = #"\d+";
flongValidate.ForeColor = System.Drawing.Color.Red;
flongValidate.Attributes["style"] = "display:block";
Controls.Add(flongValidate);
Literal colEnd = new Literal();
colEnd.Text = "</div>";
Controls.Add(colEnd);
//Add new Textbox
Literal col2 = new Literal();
col2.Text = "<div class='col-xs-4'>";
Controls.Add(col2);
TextBox fWide = new TextBox();
fWide.ID = "fWide";
fWide.CssClass = "form-control";
fWide.Text = FWide;
Controls.Add(fWide);
Literal textWide = new Literal();
textWide.Text = "<span>ft. wide</span>";
Controls.Add(textWide);
RegularExpressionValidator fwideValidate = new RegularExpressionValidator();
fwideValidate.ControlToValidate = "fWide";
fwideValidate.ErrorMessage = "Only Numbers allowed";
fwideValidate.ValidationExpression = #"\d+";
fwideValidate.ForeColor = System.Drawing.Color.Red;
fwideValidate.Attributes["style"] = "display:block";
Controls.Add(fwideValidate);
Literal col2End = new Literal();
col2End.Text = "</div>";
Controls.Add(col2End);
Literal rowEnd = new Literal();
rowEnd.Text = "</div>";
Controls.Add(rowEnd);
}
Code handling recreating (SurfaceCalculator.cs):
private int DefaultAmountControls = 1;
private string surfaceID;
public string SurfaceID
{
get { return surfaceID; }
set { surfaceID = value; }
}
public int Visibility
{
get
{
//store the object in session if not already stored
if (Session[surfaceID] == null)
Session[surfaceID] = DefaultAmountControls;
//return the object from session
return (int)Session[surfaceID];
}
set
{
if (value <= 5)
Session[surfaceID] = value;
else
Session[surfaceID] = 5;
}
}
protected void addSurface_Click(object sender, EventArgs e)
{
LinkButton b = (LinkButton)sender;
surfaceID = b.CommandArgument;
Visibility += 1;
}
protected override void OnInit(EventArgs e)
{
LinkButton addSurface = new LinkButton();
addSurface.Text = "+ Add surface";
addSurface.CommandArgument = surfaceID;
addSurface.Click += new EventHandler(addSurface_Click);
base.OnInit(e);
List<Calculator> c = Surface.Controls.OfType<Calculator>().ToList();
for (int i = 1; i <= Visibility; i++)
{
c.ElementAt(i - 1).Visible = true;
}
if (Visibility >= 5)
{
addSurface.Enabled = false;
}
Controls.Add(addSurface);
}
Code to adding many controls depending on SQL result
protected override void OnInit(EventArgs e)
{
base.OnInit(e);
var listOfProjects = //GETTING FROM SQL
if(listOfProjects != null)
{
foreach (var proj in listOfProjects)
{
Panel placeHolder = new Panel();
placeHolder.CssClass = "surface";
placeHolder.ID = "placeHolder" + proj.DocumentID;
surfacesContainer.Controls.Add(placeHolder);
SurfaceCalculator newElement = (SurfaceCalculator)LoadControl("~/PATH_TO/CONTROL.ascx");
newElement.ID = "surfaceCalculator" + proj.DocumentID;
newElement.SurfaceID = newElement.ID;
placeHolder.Controls.Add(newElement);
}
}
}

Trying to use ASCX control for file upload inside an update panel

So I have an ascx control for file upload. This control has a FileUpload element and an imagebutton in a table, as well as a grid to display the uploaded file when done.
The grid and the fileupload+imagebutton table are never visible at the same time.
The imagebutton's click event is in the ascx.cs file:
public void btnUploadFile_Click(object sender, EventArgs e)
{
try
{
if (fileUpload.HasFile)
//if(!string.IsNullOrEmpty(fileUpload.FileName))
{
String fileName = fileUpload.FileName;// strPath.Substring(lastIndex + 1);
String ext = fileUpload.FileName.Split('.')[1];
Guid newFileName = Guid.NewGuid();
string strPath = MapPath("~/importfiles/") + newFileName.ToString() + "." + ext;
fileUpload.SaveAs(strPath);
LoadTable(fileName);
hfFilePath.Value = strPath;
hfFileName.Value = fileName;
hfMIMEType.Value = fileUpload.PostedFile.ContentType;
hfFileGUID.Value = newFileName.ToString();
hfFileUploaded.Value = "1";
}
else
{
grdAttachment.Visible = false;
filePickTable.Visible = true;
}
}
catch (Exception ex)
{
UserInterfaceExceptionHandler.HandleException(ref ex);
}
}
On the content page, I have to test whether the control already has a file or not in order to know which view to display of the control (grid vs fileupload).
if (attr.ImageValue != null)
{
//Do stuff to display grid instead of fileupload control
PostBackTrigger newTrigger = new PostBackTrigger();
newTrigger.ControlID = attrControl.ID;
IssueUpdatePanel.Triggers.Add(newTrigger);
}
else
{
(attrControl.FindControl("filePickTable") as Table).Width = new Unit("200px");
ImageButton btnUploadFile = attrControl.FindControl("btnUploadFile") as ImageButton;
AsyncPostBackTrigger newTrigger = new AsyncPostBackTrigger();
newTrigger.ControlID = btnUploadFile.ID;
newTrigger.EventName = "Click";
IssueUpdatePanel.Triggers.Add(newTrigger);
}
Now the problem I am facing is that the else code (for when there is no file), I get the following exception:
Could not find an event named 'Click' on associated control 'btnUploadFile' for the trigger in UpdatePanel 'IssueUpdatePanel'.
The page has a Timer which auto refreshes the page every few seconds.
I tried looking everywhere for a solution, but to no avail.
Hopefully I have given enough information on here.

Using PostBackUrl, Getting PreviousPage.Control()

I'm using PostBackUrl to post my control from a "firstwebpage.aspx" to a "secondwebpage.aspx" so that I would be able to generate some configuration files.
I do understand that I can make use of PreviousPage.FindControl("myControlId") method in my secondwebpage.aspx to get my control from "firstwebpage.aspx"and hence grab my data and it worked.
However, it seems that this method does not work on controls which I generated programmically during runtime while populating them in a table in my firstwebpage.aspx.
I also tried using this function Response.Write("--" + Request["TextBox1"].ToString() + "--");
And although this statement do printout the text in the textfield on TextBox1, it only return me the string value of textbox1. I am unable to cast it to a textbox control in the following format too
TextBox temptextBox = (TextBox)Request["TextBox1"];
My question is, how can I actually access the control which i generated programmically in "firstwebpage.aspx" on "secondwebpage.aspx"?
Please advice!
thanks alot!
//my panel and button in aspx
<asp:Panel ID="Panel2" runat="server"></asp:Panel>
<asp:Button ID="Button1" runat="server" Text="Generate Xml" PostBackUrl="~/WebForm2.aspx" onclick="Button1_Click" />
//this is my function to insert a line into the panel
public void createfilerow(string b, string path, bool x86check, bool x86enable, bool x64check, bool x64enable)
{
Label blank4 = new Label();
blank4.ID = "blank4";
blank4.Text = "";
Panel2.Controls.Add(blank4);
CheckBox c = new CheckBox();
c.Text = b.Replace(path, "");
c.Checked = true;
c.ID = "1a";
Panel2.Controls.Add(c);
CheckBox d = new CheckBox();
d.Checked = x86check;
d.Enabled = x86enable;
d.ID = "1b";
Panel2.Controls.Add(d);
CheckBox e = new CheckBox();
e.Checked = x64check;
e.Enabled = x64enable;
e.ID = "1c";
Panel2.Controls.Add(e);
}
//my virtual path in WebForm2.aspx
<%# PreviousPageType VirtualPath="~/WebForm1.aspx" %>
//my pageload handler
protected void Page_Load(object sender, EventArgs e)
{
if (PreviousPage != null)
{
CheckBox tempCheckbox = (CheckBox)Page.PreviousPage.FindControl("1a");
Button1.Text = tempCheckbox.Text;
}
}
//handler which will populate the panel upon clicking
protected void Button7_Click(object sender, EventArgs e)
{
//get foldername
if (!Directory.Exists(#"myfilepath" + TextBox2.Text))
{
//folder does not exist
//do required actions
return;
}
string[] x86files = null;
string[] x64files = null;
string[] x86filespath = null;
string[] x64filespath = null;
ArrayList common = new ArrayList();
if (Directory.Exists(#"myfilepath" + TextBox2.Text + "\\x86"))
x86files = Directory.GetFileSystemEntries("myfilepath" + TextBox2.Text + "\\x86");
if (Directory.Exists(#"myfilepath" + TextBox2.Text + "\\x64"))
x64files = Directory.GetFileSystemEntries("myfilepath" + TextBox2.Text + "\\x64");
//some codes to convert x64files and x86files to string[]
//The header for Panel, 4 column
Label FL = new Label();
FL.ID = "flavourid";
FL.Text = "Flavour";
Panel2.Controls.Add(FL);
Label filetext = new Label();
filetext.ID = "filenamelabel";
filetext.Text = "File(s)";
Panel2.Controls.Add(filetext);
Label label86 = new Label();
label86.ID = "label86";
label86.Text = "x86";
Panel2.Controls.Add(label86);
Label label64 = new Label();
label64.ID = "label64";
label64.Text = "x64";
Panel2.Controls.Add(label64);
//a for loop determine number of times codes have to be run
for (int a = 0; a < num; a++)
{
ArrayList location = new ArrayList();
if (//this iteration had to be run)
{
string path = null;
switch (//id of this iteration)
{
case id:
path = some network address
}
//check the current version of iternation
string version = //version type;
//get the platform of the version
string platform = //platform
if (curent version = certain type)
{
//do what is required.
//build a list
}
else
{
//normal routine
//do what is required
//build a list
}
//populating the panel with data from list
createflavourheader(a);
//create dynamic checkboxes according to the list
foreach(string s in list)
//createrow parameter is by version type and platform
createfilerow(readin, path, true, true, false, false);
}
}
}
form1.Controls.Add(Panel2);
}
Sorry can't show you the full code as it is long and I believe it should be confidential even though i wrote them all
Yes you can access, Below is an example
// On Page1.aspx I have a button for postback
<asp:Button ID="btnSubmit" runat="server" Text="Submit"
PostBackUrl="~/Page2.aspx" />
// Page1.aspx.cs
protected void Page_Load(object sender, EventArgs e)
{
TextBox t = new TextBox(); // created a TextBox
t.ID = "myTextBox"; // assigned an ID
form1.Controls.Add(t); // Add to form
}
Now on the second page I will get the value of TextBox as
// Page2.aspx.cs
protected void Page_Load(object sender, EventArgs e)
{
if (PreviousPage != null)
{
TextBox t = (TextBox) PreviousPage.FindControl("myTextBox");
string mytboxvalue = t.Text;
}
// OR
string myTextBoxValue = Request.Form["myTextBox"];
}
Updated Answer:
Panel myPanel = new Panel();
myPanel.ID = "myPanel";
TextBox t = new TextBox();
t.ID = "myTextBox";
myPanel.Controls.Add(t);
TextBox t1 = new TextBox();
t1.ID = "myTextBox1";
myPanel.Controls.Add(t1);
// Add all your child controls to your panel and at the end add your panel to your form
form1.Controls.Add(myPanel);
// on the processing page you can get the values as
protected void Page_Load(object sender, EventArgs e)
{
if (PreviousPage != null)
{
TextBox t = (TextBox) PreviousPage.FindControl("myTextBox");
string mytboxvalue = t.Text;
}
string myTextBoxValue = Request.Form["myTextBox1"];
}
I also tried using this function Response.Write("--" +
Request["TextBox1"].ToString() + "--"); And although this statement do
printout the text in the textfield on TextBox1, it only return me the
string value of textbox1. I am unable to cast it to a textbox control
in the following format too
TextBox temptextBox = (TextBox)Request["TextBox1"];
Hi lw,
I think you may try passing the type of control (e.g. 'tb') together with the content and creating a new object (e.g. TextBox) and assign it to templtexBox object.
My 20 cents.
Andy

Dynamic textfields does not retain data on postback

I created a webform that allows the user to dynamically add more textboxes. Right now, as the button is clicked to add another field, it postbacks to itself. The controls are added in the Pre_Init. However when the page reconstructs itself the textbox names are different each time so the data is not being retained on each postback.
protected void Page_PreInit(object sender, EventArgs e)
{
MasterPage master = this.Master; //had to do this so that controls could be added.
createNewTextField("initEnumValue",true);
RecreateControls("enumValue", "newRow");
}
private int FindOccurence(string substr)
{
string reqstr = Request.Form.ToString();
return ((reqstr.Length - reqstr.Replace(substr, "").Length) / substr.Length);
}
private void RecreateControls(string ctrlPrefix, string ctrlType)
{
string[] ctrls = Request.Form.ToString().Split('&');
int cnt = FindOccurence(ctrlPrefix);
//Response.Write(cnt.ToString() + "<br>");
if (cnt > 0)
{
for (int k = 1; k <= cnt; k++)
{
for (int i = 0; i < ctrls.Length; i++)
{
if (ctrls[i].Contains(ctrlPrefix + k.ToString()) && !ctrls[i].Contains("EVENTTARGET"))
{
string ctrlID = ctrls[i].Split('=')[0];
if (ctrlType == "newRow")
{
createNewTextField(ctrlID,false);
}
break;
}
}
}
}
}
protected void addEnum_Click(object sender, ImageClickEventArgs e)
{
int cnt = FindOccurence("enumValue");
createNewTextField("enumValue" + Convert.ToString(cnt + 1),false);
// Response.Write(cnt.ToString() + "<br>");
}
private void createNewTextField(string ID, bool button)
{
Response.Write(ID + "<br/>"); //this is where I'm getting different names each time there is a postback
if (ID != "initEnumValue") //create new line starting with the second tb.
{
LiteralControl newLine = new LiteralControl();
newLine.Text = "<br />";
this.plhEnum.Controls.Add(newLine);
}
TextBox newTb = new TextBox();
newTb.ID = ID;
this.plhEnum.Controls.Add(newTb);
if (button) //create the button only on the first one.
{
LiteralControl space = new LiteralControl();
space.Text = " ";
this.plhEnum.Controls.Add(space);
ImageButton imgbutton = new ImageButton();
imgbutton.ID = "addEnum";
imgbutton.ImageUrl = "~/images/add.png";
imgbutton.Click += new ImageClickEventHandler(addEnum_Click);
imgbutton.CausesValidation = false;
this.plhEnum.Controls.Add(imgbutton);
}
//endEnumRow();
//this.plhEnum.Controls.Add(newTb);
}
I have tried this solution How can I get data from dynamic generated controls in ASP .NET MVC?

Pass 2 parameters to Silverlight control from SharePoint web part project into Silverlight application

I have 2 parameters defined in SharePoint web part project, meant to be passed into Application_Startup() in a Silverlight application when a user selects from 2 combo boxes (browsable properties). Somehow the Silverlight control does not render when i load it on the SharePoint site. With 1 parameter passed in, the control displays without error. Any ideas? Syntax? Examples?
App.xaml.cs:
private void Application_Startup(object sender, StartupEventArgs e)
{
//testing
string _setArticles = null;
string _setLength = null;
if (e.InitParams != null && e.InitParams.Count >= 1)
{
_setArticles = e.InitParams["_setArticles"];
_setLength = e.InitParams["_setLength"];
}
this.RootVisual = new Page(_setArticles, _setLength);
}
Page.xaml.cs:
public Page(string _setArticles, string _setLength)
{
InitializeComponent();
//(number of items to display on load)
if (!string.IsNullOrEmpty(_setArticles) && !string.IsNullOrEmpty(_setLength) )
{
if (_setArticles.Equals("_1_article"))
retrieveOneListboxItemStaffNews();
GetData3();
if (_setArticles.Equals("_2_articles"))
retrieveTwoListboxItemStaffNews();
GetData3();
if (_setArticles.Equals("_3_articles"))
retrieveThreeListboxItemStaffNews();
GetData3();
//testing
//send value to method 'fullNameControl_Loaded' (summary length of each ListBox item)
if (_setLength.Equals("_3_lines"))
m_textBlock.MaxHeight = 40;
if (_setLength.Equals("_4_lines"))
m_textBlock.MaxHeight = 50;
if (_setLength.Equals("_5_lines"))
m_textBlock.MaxHeight = 65;
}
}
SilverlightSecondWebPart.cs:
protected override void CreateChildControls()
{
base.CreateChildControls();
//silverlight control
silverlightControl = new Silverlight();
silverlightControl.ID = "News";
silverlightControl.Source = "/ClientBin/News.xap";
silverlightControl.Width = new System.Web.UI.WebControls.Unit(800);
silverlightControl.Height = new System.Web.UI.WebControls.Unit(550);
//testing
string parameters = "_setArticles=" + _myEnum + ", " + "_setLength=" + _myEnum2;
silverlightControl.InitParameters = parameters;
silverlightControl.MinimumVersion = "2.0";
Controls.Add(silverlightControl);
}
Anyway use
if (_setArticles.Equals("_1_article"))
{
retrieveOneListboxItemStaffNews();
GetData3();
}
if (_setArticles.Equals("_2_articles"))
{
retrieveTwoListboxItemStaffNews();
GetData3();
}
if (_setArticles.Equals("_3_articles"))
{
retrieveThreeListboxItemStaffNews();
GetData3();
}
otherwise GetData3() will be called anyway, 3 times each time.

Categories

Resources