I cannot get anything other than a null value from my drop down box, im trying to upload files to different directories...
public class dropDownInfo
{
public string pathName { get; set; }
public string pathValue { get; set; }
}
string uploadFolder = "";
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
// reference to directory
//DirectoryInfo di = new DirectoryInfo("//DOCSD9F1/TECHDOCS/");
DirectoryInfo di = new DirectoryInfo("D:/SMGUpload/SMGUpload/files/");
// create list of directories
List<dropDownInfo> DropDownList = new List<dropDownInfo>();
foreach (DirectoryInfo i in di.GetDirectories())
{
dropDownInfo ddInfo = new dropDownInfo();
ddInfo.pathName = i.FullName;
ddInfo.pathValue = i.FullName;
DropDownList.Add(ddInfo);
}
DropDownList1.DataSource = DropDownList;
DropDownList1.DataTextField = "pathName";
DropDownList1.DataValueField = "pathValue";
DropDownList1.DataBind();
}
}
protected void DropDownList1_IndexChanged(object sender, EventArgs e)
{
uploadFolder = DropDownList1.SelectedItem.Value;
}
protected void ASPxUploadControl1_FileUploadComplete(object sender, DevExpress.Web.ASPxUploadControl.FileUploadCompleteEventArgs e)
{
if (e.IsValid)
{
string uploadDirectory = Server.MapPath("~/files/");
//string uploadDirectory = #"\\DOCSD9F1\TECHDOCS\";
string fileName = e.UploadedFile.FileName;
//string uploadFolder = DropDownList1.SelectedValue;
//string path = (uploadDirectory + uploadFolder + "/" + fileName);
string path = Path.Combine(Path.Combine(uploadDirectory, uploadFolder), fileName);
e.UploadedFile.SaveAs(path);
e.CallbackData = fileName;
}
}
Do a check before you access the Value property.
if (DropDownList1.SelectedItem != null)
uploadFolder = DropDownList1.SelectedItem.Value;
The dropdown has no values after postback. You are only binding at first page load, then the page posts back (index changed) and the items are not re-bound.
Do you have viewstate disabled on the page or any of the controls? This could cause the issue you are describing.
Also, the local variable uploadFolder will never be preserved between post backs. You need to store it in the session or on the page somewhere.
Session["uploadFolder"] = DropDownList1.SelectedItem.Value
You need to re-set the DataSource on post back, but don't re-bind it or that will reset the selected index as well.
Related
I always wanted my code to be cleaner and readable. I'm here in order to achieve that. Since i'm a beginner, it's better to learn this early. Like calling all of them in a class, I don't want too see these many codes in my form. I hope someone would be able to give me a suggestions and a proper way of doing these.
Here's my code
public partial class SIMSSupplier : UserControl
{
ADDSupplier supply;
ADDPReturns returns;
public SIMSSupplier()
{
InitializeComponent();
}
public DataTable dbdataset;
public DataSet ds = new DataSet();
public string ID = "SPPLR-000";
public int DeliveryID, OrderID, ReturnID;
DataView db;
DataTable dt = new DataTable();
private void Supplierview_SelectionChanged(object sender, EventArgs e)
{
var row = Supplierview.CurrentCell.RowIndex;
SupplierID.Text = Supplierview.Rows[row].Cells[0].Value.ToString();
CompanyName.Text = Supplierview.Rows[row].Cells[1].Value.ToString();
ContactName.Text = Supplierview.Rows[row].Cells[2].Value.ToString();
ContactNumber.Text = Supplierview.Rows[row].Cells[3].Value.ToString();
Date.Text = Supplierview.Rows[row].Cells[4].Value.ToString();
Address.Text = Supplierview.Rows[row].Cells[5].Value.ToString();
Remarks.Text = Supplierview.Rows[row].Cells[6].Value.ToString();
}
private void PurchaseOrder_SelectionChanged(object sender, EventArgs e)
{
var row = PurchaseOrder.CurrentCell.RowIndex;
txt_purchase.Text = PurchaseDeliveries.Rows[row].Cells[0].Value.ToString();
txt_supplier.Text = PurchaseDeliveries.Rows[row].Cells[1].Value.ToString();
txt_item.Text = PurchaseDeliveries.Rows[row].Cells[2].Value.ToString();
txt_date.Text = PurchaseDeliveries.Rows[row].Cells[3].Value.ToString();
txt_quantity.Text = PurchaseDeliveries.Rows[row].Cells[4].Value.ToString();
txt_cost.Text = PurchaseDeliveries.Rows[row].Cells[5].Value.ToString();
txt_amount.Text = PurchaseDeliveries.Rows[row].Cells[6].Value.ToString();
txt_sales.Text = PurchaseDeliveries.Rows[row].Cells[7].Value.ToString();
txt_code.Text = PurchaseDeliveries.Rows[row].Cells[8].Value.ToString();
txt_patient.Text = PurchaseDeliveries.Rows[row].Cells[9].Value.ToString();
}
private void PurchaseDeliveries_SelectionChanged(object sender, EventArgs e)
{
var row = PurchaseDeliveries.CurrentCell.RowIndex;
PurchaseID.Text = PurchaseDeliveries.Rows[row].Cells[0].Value.ToString();
Supplier.Text = PurchaseDeliveries.Rows[row].Cells[1].Value.ToString();
ItemDescription.Text = PurchaseDeliveries.Rows[row].Cells[2].Value.ToString();
Dates.Text = PurchaseDeliveries.Rows[row].Cells[3].Value.ToString();
Quantity.Text = PurchaseDeliveries.Rows[row].Cells[4].Value.ToString();
Unitcost.Text = PurchaseDeliveries.Rows[row].Cells[5].Value.ToString();
Amount.Text = PurchaseDeliveries.Rows[row].Cells[6].Value.ToString();
SalesInvoice.Text = PurchaseDeliveries.Rows[row].Cells[7].Value.ToString();
Codeitems.Text = PurchaseDeliveries.Rows[row].Cells[8].Value.ToString();
Patientname.Text = PurchaseDeliveries.Rows[row].Cells[9].Value.ToString();
}
private void PurchaseReturn_SelectionChanged(object sender, EventArgs e)
{
var row = PurchaseReturn.CurrentCell.RowIndex;
txt_return.Text = PurchaseReturn.Rows[row].Cells[0].Value.ToString();
txt_rsupplier.Text = PurchaseReturn.Rows[row].Cells[1].Value.ToString();
txt_ritem.Text = PurchaseReturn.Rows[row].Cells[2].Value.ToString();
txt_rmodel.Text = PurchaseReturn.Rows[row].Cells[3].Value.ToString();
txt_rsrp.Text = PurchaseReturn.Rows[row].Cells[4].Value.ToString();
txt_rcode.Text = PurchaseReturn.Rows[row].Cells[5].Value.ToString();
txt_rdate.Text = PurchaseReturn.Rows[row].Cells[6].Value.ToString();
txt_rremarks.Text = PurchaseReturn.Rows[row].Cells[7].Value.ToString();
}
}
the first can simplify as the following:
private void Supplierview_SelectionChanged(object sender, EventArgs e)
{
var row = Supplierview.CurrentRow;
SupplierID.Text = row.Cells[0].Value.ToString();
CompanyName.Text = row.Cells[1].Value.ToString();
ContactName.Text = row.Cells[2].Value.ToString();
ContactNumber.Text = row.Cells[3].Value.ToString();
Date.Text = row.Cells[4].Value.ToString();
Address.Text = row.Cells[5].Value.ToString();
Remarks.Text = row.Cells[6].Value.ToString();
}
the second , i would recommend use objects collection as a datasource for your grid. For example :
class DataItem{
public string SupplierID {get;set;}
public string CompanyName {get;set;}
.....
}
Supplierview.DataSource = "collection of DataItem"
then
private void Supplierview_SelectionChanged(object sender, EventArgs e)
{
var dataItem = dataGridView1.CurrentRow.DataBoundItem as DataItem;
if (dataItem != null)
{
SupplierID.Text = dataItem.SupplierID;
.....
}
}
I suggest using DataBinding for this, then there is no code needed to perform the actions in your sample.
If you dont want to use databinding you could simply make use of private methods to organize your code.
For example
#region Supplier Stuff
private void SupplierViewChanged(DataRow row)
{
SupplierID.Text = row.Cells[0].Value.ToString();
CompanyName.Text = row.Cells[1].Value.ToString();
ContactName.Text = row.Cells[2].Value.ToString();
ContactNumber.Text = row.Cells[3].Value.ToString();
Date.Text = row.Cells[4].Value.ToString();
Address.Text = row.Cells[5].Value.ToString();
Remarks.Text = row.Cells[6].Value.ToString();
}
// put all other helper methods that deal with Supplier here...
#endregion Supplier Stuff
private void Supplierview_SelectionChanged(object sender, EventArgs e)
{
SupplierViewChanged(Supplierview.CurrentRow);
}
This makes your code a bit more organized and readable, but databinding is still the method I would choose
I am using a aspx webpage with C# and I'm trying to point to a directory but when I do so, I get "Could not find file 'c:\windows\system32\inetsrv\2.txt'." But in my C# code, I am using:
currentStaffPosition = rolesRadioButton.SelectedItem.ToString();
string currentStaffDirectory = Server.MapPath(#"~\admin\applications\" + currentStaffPosition);
This code should point to C:\inetpub\wwwroot\admin\applications
Anyone know why or how this is happening? Thanks ahead of time.
Additional Code:
string currentStaffPosition = null;
string currentStaffDirectory = null;
protected void rolesRadioButton_SelectedIndexChanged(object sender, EventArgs e)
{
dropDownList.Items.Clear();
currentStaffPosition = rolesRadioButton.SelectedItem.ToString();
string currentStaffDirectory = Server.MapPath(#"~\admin\applications\" + currentStaffPosition);
string[] staffApplications = Directory.GetFiles(currentStaffDirectory);
foreach (string apps in staffApplications)
{
dropDownList.Items.Add(new ListItem(Path.GetFileNameWithoutExtension(apps)));
}
}
protected void dropDownList_SelectedIndexChanged(object sender, EventArgs e)
{
string currentSelectedApp = currentStaffDirectory + dropDownList.SelectedItem + ".txt";
string currentLine;
StreamReader applicationReader = new StreamReader(currentSelectedApp);
while ((currentLine = applicationReader.ReadLine()) != null)
{
if (currentLine.Contains("First Name:"))
forumUsernameTextBox.Text = currentLine.Replace("First Name: ", "");
}
applicationReader.Close();
}
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)
}
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
I have the following Javascript:
function processText(n)
{
CallServer("1" + n.id + "&" + n.value, "");
}
function ReceiveServerData(arg, context)
{
alert(arg);
}
With this for my code-behind:
protected void Page_Load(object sender, EventArgs e)
{
ClientScriptManager cm = Page.ClientScript;
String cbRef = cm.GetCallbackEventReference(this, "arg", "ReceiveServerData", "context");
String callbackscript = "function CallServer(arg, context) {" + cbRef + "; }";
cm.RegisterClientScriptBlock(this.GetType(), "CallServer", callbackscript, true);
if (Request.QueryString["stationID"] != null)
{
isIndividual = true;
stationID = Request.QueryString["stationID"];
EncodeDecode objServers = new EncodeDecode(HttpContext.Current.Server.MapPath("~/App_Data/"));
if (!IsPostBack)
{
List<IServerConfig> serverConfig = objServers.GetServerConfiguration(stationID);
Session["ServerConfig"] = serverConfig;
Session["dctPropertyControls"] = new Dictionary<string, PropertyObj>();
}
BindDynamicControls(Session["ServerConfig"] as List<IServerConfig>);
}
}
public void RaiseCallbackEvent(String eventArgument)
{
int iTyped = int.Parse(eventArgument.Substring(0, 1).ToString());
if (iTyped != 0) //Process Text Fields
{
string controlName = eventArgument.Substring(1, eventArgument.IndexOf("&")).ToString();
string controlValue = eventArgument.Substring(eventArgument.IndexOf("&")).ToString();
//Txtid += -1;
Dictionary<string, PropertyObj> dctPropertyObj = Session["dctPropertyControls"] as Dictionary<string, PropertyObj>;
PropertyObj propertyObj = dctPropertyObj[controlName];
propertyObj.property.SetValue(propertyObj.owner, controlValue, null);
this.sGetData = "Done";
}
}
public String GetCallbackResult()
{
return this.sGetData;
}
processText gets fired and works, however RaiseCallbackEvent never fires. Any ideas?
Apparently, any sort of validation error will cause this, though the page will never tell you about it. In my case, I had two datalists on the page with the same id. I had to debug the javascript and read the xmlRequest to see the error.
Sorry if replying late but may help others..
ValidationRequest="false" at .aspx page may sort out this unidentified problem.