'String' does not contain a reference for 'Text' - asp.net

The .Text on add is giving the error, I believe I have the right assemblies in place.
StringCollection sc = new StringCollection();
for (int i = 1; i <= 2; i++)
{
//extract the TextBox values
string txt1 = ((TextBox)Page.FindControl("TextBox1" + i.ToString())).Text;
string txt2 = ((TextBox)Page.FindControl("TextBox2" + i.ToString())).Text;
string txt3 = ((TextBox)Page.FindControl("TextBox3" + i.ToString())).Text;
string txt4 = ((TextBox)Page.FindControl("TextBox4" + i.ToString())).Text;
string txt5 = ((TextBox)Page.FindControl("TextBox5" + i.ToString())).Text;
string txt6 = ((TextBox)Page.FindControl("TextBox6" + i.ToString())).Text;
string txt7 = ((TextBox)Page.FindControl("TextBox7" + i.ToString())).Text;
string txt8 = ((TextBox)Page.FindControl("TextBox8" + i.ToString())).Text;
string txt9 = ((TextBox)Page.FindControl("TextBox9" + i.ToString())).Text;
sc.Add(txt1.Text, txt2.Text, txt3.Text, txt4.Text, txt5.Text, txt6.Text, txt7.Text, txt8.Text, txt9.Text);
}
InsertRecords(sc);

You are basically calling string.Text since the type of txt1, txt2, etc is string, hence the error. But note that you are already calling .Text on the TextField control so what you probably intend to do is:
sc.AddRange(new string[]{txt1, txt2, txt3, ...});

Related

ASP.NET MVC session gets null after IO operation

Here is the code I wrote.
if (propertyModel.PropertyName.Replace(" ", "") != model.PropertyName.Replace(" ", "") && propertyModel.PropertyRegistrationCompletedPercentage >= 71)
{
var originalDirectory = new DirectoryInfo(string.Format("{0}Images\\ProprtyImages", Server.MapPath(#"\")));
string pathString = System.IO.Path.Combine(originalDirectory.ToString(), propertyModel.PropertyName.Replace(" ", "") + "__" + User.Identity.GetUserId().Replace("-", "") + "__" + "propertyid" + "__" + propertyModel.PropertyId.ToString());
string newpathstring = System.IO.Path.Combine(originalDirectory.ToString(), model.PropertyName.Replace(" ", "") + "__" + User.Identity.GetUserId().Replace("-", "") + "__" + "propertyid" + "__" + propertyModel.PropertyId.ToString());
bool isExists = System.IO.Directory.Exists(pathString);
if (isExists)
{
Directory.Move(pathString, newpathstring);
}
else
{
ViewBag.Message = "Unexpected IO error occurred.";
return View("ErrorPageWithCustomMessage");
}
}
Session["PropertyRegistrationCompletedPercentage"] = propertyModel.PropertyRegistrationCompletedPercentage;
Session["IsPropertyBeingStartedToAdd"] = propertyModel.IsPropertyBeingStartedToAdd;
Session["IsPropertyAddingCompleted"] = propertyModel.IsPropertyAddingCompleted;
Session["IsThePropertyVerified"] = propertyModel.IsThePropertyVerified;
When I try to retrieve session variable after redirecting in to an another action those values are gone how to fix this?

How to take a result on another page in asp.net?

Image1.Visible = true;
Label2.Text = "Correct Ans = " + answer.ToString();
Label3.Text = "Incorrect Ans = " + wrong.ToString();
Label20.Text = "Total Questions = " + count.ToString();
Label21.Text = "Score = " + answer* 10;
Label26.Text = "Percentage = " + Math.Round(answer / count* 100)+ " %";
answer = 0;
wrong = 0;
There are many different ways to achieve this.I would suggest you read A Beginner's Tutorial on ASP.NET State Management and decide which one suits you best
Here's a simple example which uses three of these technologies, namely:
Query strings
Session state
Cookies
Setting values:
string name = txtName.Text;
//1.Session
Session["name"] = name;
//2.Cookies
Response.Cookies["name"].Value = name;
Response.Cookies["name"].Expires = DateTime.Now.AddDays(1);
//3.Query strings
Response.Redirect("Page2.aspx?name=" + name);
Reading values:
//1.Session
string nameFromSession = Session["name"] as string;
//2.Cookies
string nameFromCookie = Request.Cookies["name"].Value;
//3.Query strings
string nameFromQueryString = Request.QueryString["name"];

Unable to convert webcontrol to generic type in asp.net c#

I have the below method that I am using to create webcontrols (for now just literal and Panel)
private T CreateControl<T>(string s1, string s2, string m1)
where T: WebControl , new()
{
T ctrl = default(T);
if (ctrl is Literal )
{
Literal l = new Literal();
l.ID = s1 + "ltl" + s2;
l.Text = s1 + " " + s2;
ctrl = (Literal)l;
}
else if (ctrl is Panel)
{
Panel p = new Panel();
p.ID = s1+ "pnl" + s2;
p.CssClass = s1 + "graphs";
p.Attributes.Add("responsefield", s2);
p.Attributes.Add("metricid", m1);
ctrl = (Panel)l;
}
else if (ctrl is CheckBox)
return ctrl;
}
I am invoking this as:
Literal lg = CreateControl<Literal>("emails", name.Name, name.MetricId.ToString() );
But the conversion is failing at:
ctrl = (Literal)l;
ctrl = (Panel)p;
Error:
Cannot implicitly convert type 'System.Web.UI.WebControls.Panel' to 'T'
Can somebody advise how to handle this conversion?
Thanks in advance...
I can suggest you something like this.
private T CreateControl<T>(string s1, string s2, string m1)
where T : System.Web.UI.Control,new()
{
if (typeof(T) == typeof(Literal))
{
Literal l = new Literal();
l.ID = s1 + "ltl" + s2;
l.Text = s1 + " " + s2;
return l as T;
}
else if (typeof(T) == typeof(Panel))
{
Panel p = new Panel();
p.ID = s1 + "pnl" + s2;
p.CssClass = s1 + "graphs";
p.Attributes.Add("responsefield", s2);
p.Attributes.Add("metricid", m1);
return p as T;
}
else if (typeof(T) == typeof(CheckBox))
{
return new CheckBox() as T;
}
else
{
return new T();
}
}
Edit: Modified the method you don't need to cast it afterwars like #jbl suggested.
Literal l = CreateControl<Literal>("something", "something", "something");

Saving Multiple Image Path url in Database at once

My multiple image upload code works fine. But while inserting the image path url in the database only one image path is saved. How can i save all the image path url's at once.
Here is my GetPictureData()
public string GetPictureData()
{
string retFileName = "";
try
{
if (((FileUpload1.PostedFile != null)))
{
if ((FileUpload1.PostedFile.ContentType.ToUpper().Contains("IMAGE")))
{
HttpFileCollection hfc = Request.Files;
for (int i = 0; i < hfc.Count; i++)
{
HttpPostedFile hpf = hfc[i];
if (hpf.ContentLength > 0)
{
//Stream inStream = hpf.InputStream;
//byte[] fileData = new byte[hpf.ContentLength];
//inStream.Read(fileData, 0, hpf.ContentLength);
String sTimeStamp = GetTimeStamp();
string iFileName = System.IO.Path.GetFileName(hpf.FileName);
string newFileName = iFileName.Replace(" ", "_");
string OutFile = Server.MapPath(ConfigurationManager.AppSettings["LocalImageDirectory"]) + "\\" + sTimeStamp + "_" + newFileName;
hpf.SaveAs(OutFile);
OutFile = ConfigurationManager.AppSettings["LocalImageDirectory"] + "\\" + sTimeStamp + "_" + newFileName;
retFileName = OutFile;
}
}
}
}
}
catch(Exception ex)
{
string msg = ex.Message;
Response.Write(msg);
}
return retFileName;
}
and here is my UploadButton code
protected void btnUpload_Click(object sender, EventArgs e)
{
if (Session["localauctionid"] != null && Session["localauctionid"].ToString() != "")
{
string filepath = GetPictureData();
if (filepath != "")
{
string sqlcommand = " insert into auctionimages (auctionid, ImagePath, GalleryPic) values(" + Session["localauctionid"].ToString() + ",'" + filepath + "', 0);" +
" update auctionstep1 set ListingStatus = 'Photographed' where auctionid = " + Session["localauctionid"].ToString() + " and (listingstatus <> 'Created' AND listingstatus <> 'Saved');";
Database db = DatabaseFactory.CreateDatabase();
DbCommand cmd = db.GetSqlStringCommand(sqlcommand);
db.ExecuteNonQuery(cmd);
LoadImages();
}
}
}
Thanks
You error lies in the fact that the GetPictureData loops over a collection of files, but only the last file is returned to the button event where you call the save to database code. Of course, only the last file will be saved in the database.
The workaround is to create a standalone method to save in the database where you pass the filename and the localAuctionID. You call this method inside the GetPictureData (renamed more correctly to SavePictureData) internal loop for each file to be saved
As a pseudocode (not tested)
private void SaveToDb(int localAutID, string filepath)
{
string sqlcommand = " insert into auctionimages (auctionid, ImagePath, GalleryPic) " +
"values(#auID, #file, 0); " +
" update auctionstep1 set ListingStatus = 'Photographed' " +
"where auctionid = #auID and (listingstatus <> 'Created' " +
"AND listingstatus <> 'Saved');";
Database db = DatabaseFactory.CreateDatabase();
DbCommand cmd = db.GetSqlStringCommand(sqlcommand);
DbParameter p1 = cmd.CreateParameter()
{ParameterName="#auID", DbType=DbType.Int32, Value=localAutID};
DbParameter p2 = cmd.CreateParameter()
{ParameterName="#file", DbType=DbType.AnsiString, Value=filepath};
db.ExecuteNonQuery(cmd);
}
And if SavePictureData call it inside the for loop
for (int i = 0; i < hfc.Count; i++)
{
.....
retFileName = OutFile;
SaveToDb(Convert.ToInt32(Session["localauctionid"]), retFileName);
}
if (Session["localauctionid"] != null && Session["localauctionid"].ToString() != "")
{
string filepath = GetPictureData();
if (filepath != "")
{
string sqlcommand = " insert into auctionimages (auctionid, ImagePath, GalleryPic) values(" + Session["localauctionid"].ToString() + ",'" + filepath + "', 0);" +
" update auctionstep1 set ListingStatus = 'Photographed' where auctionid = " + Session["localauctionid"].ToString() + " and (listingstatus <> 'Created' AND listingstatus <> 'Saved');";
Database db = DatabaseFactory.CreateDatabase();
DbCommand cmd = db.GetSqlStringCommand(sqlcommand);
db.ExecuteNonQuery(cmd);
LoadImages();
}
The person only clicks the upload button once - hence only one image being saved.
Personally I would evaluate the way you have coded this. I would move the code you use to save the image to the db into a stand alone method and call it when the image upload is complete in GetPictureData()

Why Can't I store XML in ASP.NET ListBox Value?

Why does this work:
ListItem item = new ListItem();
string value = lstAvailExtPropsToFilter.SelectedItem.Text +" = "+ txtExtPropToFilter.Text;
string text = lstAvailExtPropsToFilter.SelectedItem.Text + " = " + txtExtPropToFilter.Text;
item.Text = text;
item.Value = value;
lstExtPropsToFilter.Items.Add(item);
But not this:
ListItem item = new ListItem();
string value = string.Format("<key>{0}</key><value>{1}</value>", lstAvailExtPropsToFilter.SelectedItem.Text, txtExtPropToFilter.Text);
string text = lstAvailExtPropsToFilter.SelectedItem.Text + " = " + txtExtPropToFilter.Text;
item.Text = text;
item.Value = value;
lstExtPropsToFilter.Items.Add(item);
You would have to escape the string so it works in HTML. Try Server.HTMLEncode.
Server.HTMLEncode("<key>{0}</key><value>{1}</value>")
Then when you need to pull the value you, use Server.HTMLDecode.

Resources