I have an ASP.NET WebForm with 1 button and 4 textboxes.
Every time the page loads, the following code to read data from an XML file and display in the textboxes is executed:
private void PutWhatWasBefore()
{
var xml = XDocument.Load(#"C:\Settings.xml");
From_display.Text = xml.Element("Settings").Element("Remember").Attribute("fromdisplay").Value.ToString();
From_Smtp.Text = xml.Element("Settings").Element("Remember").Attribute("fromsmtp").Value.ToString();
subject.Text = xml.Element("Settings").Element("Remember").Attribute("subject").Value.ToString();
}
This code works well, it puts everything in the textboxes. BUT, and this is a big but, when i click the button, the following code to write to the XML file does not work:
string tem = Template1.Text;
string from = From_Smtp.Text;
string dis = From_display.Text;
string sub = subject.Text;
var x = new XDocument(
new XElement("Settings",
new XElement("Remember",
new XAttribute("fromsmtp", from),
new XAttribute("subject", sub),
new XAttribute("fromdisplay", dis),
new XAttribute("template", tem)
)
)
);
x.Save(#"C:\Settings.xml");
No matter how I change the data in the text boxes, every time I click on the button the data reverts back to what it was before.
I was thinking its a post back and that's why this is happening, but even if i disable the post back with OnClientClick = return false; it still does not work.
Any ideas?
EDIT(12:06):
I don't think I have said where the problem was and I want to be more into the point.
When I click the button the following function is executed first:
private void SaveNames()
{
try
{
string tem = Template1.Text;
string from = From_Smtp.Text;
string dis = From_display.Text;
string sub = subject.Text;
var x = new XDocument(
new XElement("Settings",
new XElement("Remember",
new XAttribute("fromsmtp", "He2"),
new XAttribute("subject", sub),
new XAttribute("fromdisplay", dis),
new XAttribute("template", tem)
)
)
);
x.Save(#"C:\Program Files (x86)\ActivePath\MailSenderWeb\Settings.xml");
}
catch (Exception ex)
{
AnswerAndError.Text = ex.Message;
}
}
That's the functions that doesn't work. It just doesn't save new data into the XML file.
This should solve your issue:
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
PutWhatWasBefore();
}
}
This will ensure the code runs only when the page is initially visited.
Related
so i have an HTML table with dynamically added rows and ASP.NET text boxes. I have the rows and controls re-instantiated on page_load if the viewstate[dataonpage] = true, and I'm declaring it as true in the method that adds the rows and controls. (I need them to persist on other postbacks)
The problem is that I'm now I've added a CLEAR button that removes all of the html rows (excluding the headers) when it's clicked, and for some reason on button click it gets an index error, or if using Try/Catch it only removes half of the rows (every other row). I believe the problem is something to do with that the viewstate[dataonpage] is still "true", and the data is being re-added on page load. If i add viewstate["dataonpage"] = "false" into the clear button method, the same happens but at least this way on the second click it removes the second half of the rows.
I understand this happens because the button event handler isn't fired until after the page_load which is why it doesn't work on the first click. But what I don't fully understand is why even without this my clear button code doesn't clear all of the rows in the first place.
Any help on understanding why it doesn't work, and a work around will be greatly appreciated!
protected void Page_Load(object sender, EventArgs e)
{
if (Convert.ToString(ViewState["DataOnPage"]) == "true")
{
Getmarketdata();
}
}
protected void Getdatabtn_Click(object sender, EventArgs e)
{
ViewState["DataOnPage"] = "true";
Getmarketdata();
}
Below is method that creates adds table rows and controls:
public void Getmarketdata()
{
String url = "https://api.rightmove.co.uk/api/rent/find?index=0&sortType=1&maxDaysSinceAdded=" + Dayssinceuploadtext.Text + "&locationIdentifier=OUTCODE%5e" + Outcodetext.Text + "&apiApplication=IPAD";
Response.Write(url);
using (var webclient = new WebClient())
{
String Rawjson = webclient.DownloadString(url);
ViewState["VSMarketDataJSONString"] = Rawjson;
dynamic dobj = JsonConvert.DeserializeObject<dynamic>(Rawjson);
int NoOfHouses = dobj["properties"].Count;
Response.Write("<br />" + NoOfHouses);
for (int i = 0; i < NoOfHouses; i++)
{
System.Web.UI.HtmlControls.HtmlTableRow tRow = new System.Web.UI.HtmlControls.HtmlTableRow();
GeneratorTable.Rows.Add(tRow);
String RMlink = String.Format("https://www.rightmove.co.uk/property-to-rent/property-" + dobj["properties"][i]["identifier"].ToString()) + ".html";
HyperLink hypLink = new HyperLink();
hypLink.Text = dobj["properties"][i]["identifier"].ToString();
hypLink.Target = "_blank";
hypLink.NavigateUrl = RMlink;
using (System.Web.UI.HtmlControls.HtmlTableCell tb1 = new System.Web.UI.HtmlControls.HtmlTableCell())
{
tRow.Cells.Add(tb1);
tb1.Controls.Add(hypLink);
}
using (System.Web.UI.HtmlControls.HtmlTableCell tb2 = new System.Web.UI.HtmlControls.HtmlTableCell())
{
TextBox tbEPCe = new TextBox();
tRow.Cells.Add(tb2);
tb2.Controls.Add(tbEPCe);
String txtboxID = (("EPCETxtBox") + i);
tbEPCe.ID = txtboxID;
tbEPCe.Style.Add("background", "none"); tbEPCe.Style.Add("border", "1px solid black"); tbEPCe.Style.Add("border-radius", "2px");
}
using (System.Web.UI.HtmlControls.HtmlTableCell tb3 = new System.Web.UI.HtmlControls.HtmlTableCell())
{
TextBox tbEPCp = new TextBox();
tRow.Cells.Add(tb3);
tb3.Controls.Add(tbEPCp);
String txtboxID = (("EPCPTxtBox") + i);
tbEPCp.ID = txtboxID;
tbEPCp.Style.Add("background", "none"); tbEPCp.Style.Add("border", "1px solid black"); tbEPCp.Style.Add("border-radius", "2px");
}
using (System.Web.UI.HtmlControls.HtmlTableCell tb4 = new System.Web.UI.HtmlControls.HtmlTableCell())
{
TextBox tbBbl = new TextBox();
tRow.Cells.Add(tb4);
tb4.Controls.Add(tbBbl);
String txtboxID = (("BblTxtBox") + i);
tbBbl.ID = txtboxID;
tbBbl.Style.Add("background", "none"); tbBbl.Style.Add("border", "1px solid black"); tbBbl.Style.Add("border-radius", "2px");
}
}
}
}
Below is clear table rows method: (this is the one that isn't working)
public void ClearTableRows()
{
System.Web.UI.HtmlControls.HtmlTable Htmlgeneratortable = ((System.Web.UI.HtmlControls.HtmlTable)GeneratorTable);
int NoOfRows = Htmlgeneratortable.Rows.Count;
for (int j = 1; j < NoOfRows; j++)
{
try
{
Htmlgeneratortable.Rows.RemoveAt(j);
}
catch
{ }
}
}
I'm going to explain what's going on as you have the code written now; I don't have faith in my ability to provide an answer including the exact code changes to be made, so here is what is wrong with your current approach:
Your table, GeneratorTable exists for all clients. That doesn't mean every time someone navigates to your website a table is generated, it means that there is one table, and every client that logs in is getting that one table.
So if you add rows to it for one client, then send the table to another client, both clients will see the same table (with the rows added).
The problem is that emptying out a table is logic that has nothing to do with your back-end server. There's no reason for your server to be handling emptying a table, your server should only handle page navigations and AJAX calls pretty much, it shouldn't be changing how the webpage looks, because the server can only respond to each client one time.
What's the point in responding to a client with GeneratorTable and then updating GeneratorTable on the server? The client will never see the updates made to the table unless they're resent from the server.
You stated that you are new to this and need to learn about JS and client-side, this exercise should serve as an example of why you need to put certain code on the front-end and some code on the back-end, as there isn't really an elegeant way to do what you're looking to do with just the server.
So, I would like any help to populate a ListBox that is going to show a website name and if it's clicked go to a specific url.
This is what's inside of the text file:
#first website
http://firstwebsite.com
#second website
http://secondwebsite.com
#third website
http://thirdwebsite.com
I can read the file and populate the listbox with the name, but cannot put the url working.
FileOpenPicker picker = new FileOpenPicker();
picker.ViewMode = PickerViewMode.Thumbnail;
picker.SuggestedStartLocation = PickerLocationId.ComputerFolder;
picker.FileTypeFilter.Add(".txt");
StorageFile file = await picker.PickSingleFileAsync();
if (file != null) {
var stream = await file.OpenAsync(FileAccessMode.Read);
using (StreamReader reader = new StreamReader(stream.AsStream()))
{
while (!reader.EndOfStream)
{
string line = reader.ReadLine();
if (line.StartsWith("#") {
listbox.items.Add(line);
}
Any help is great.
Thanks
If you want it in the "Click" event, I mean when you click on the Item, below code works.
private void listBox1_Click(object sender, EventArgs e)
{
string str = ((ListBox)(sender)).Text;
Process.Start(str);
}
Handle NULL conditions and exceptions.
Add System.Diagnostics namespace for "Process".
I've created a very simple console to test this.
Here is what I came up with
var _listBox1 = new ListBox();
//just adding a url for example
_listBox1.Items.Add("http://www.google.com");
//here I am just setting the selected value
_listBox1.SetSelected(0, true);
var selectedUrl = _listBox1.SelectedItem.ToString();
//this will start off the default web browser
Process.Start(selectedUrl);
So the Process.Start() can be put in any event handlers for that listbox. I.E SelectedIndexChanged event
private void _listBox1_SelectedIndexChanged(object pSender, EventArgs pArgs)
{
var selectedUrl = _listBox1.SelectedItem.ToString();
Process.Start(selectedUrl);
}
I have a database table that I need to update records on. The code to add a new record works just fine, But when I go to update an existing record, not all the fields update with the new information in the form.
Here's the code:
private void updateExistingDSN()
{
//Update existing DSN
try
{
using (PathFinderDataContext pfdcContext = new PathFinderDataContext())
{
DSN oldDSN = pfdcContext.DSNs.Single(dsn => dsn.DSNID == int.Parse(Request["dsn"]));
oldDSN.Auth_AuthorizationID = int.Parse(Request["auth"]);
oldDSN.ServiceProvided_ServiceProvidedID = int.Parse(Request["sp"]);
oldDSN.EvidenceBPMU = short.Parse(ddlEvidenceBPMU.SelectedValue);
oldDSN.LocationOfVisit = txtLocationOfVisit.Text;
oldDSN.ChildrenPresent = txtNamesOfChildrenPresent.Text;
oldDSN.ParentPresent = txtNamesOfParentsPresent.Text;
oldDSN.OthersPresent = txtNamesOfOthersPresent.Text;
oldDSN.DescribeGoals = txtDescribeGoals.Text;
oldDSN.DescribeStrategy = txtDescribeStrategies.Text;
oldDSN.DescibeParentingSkills = txtDescribeParentingSkills.Text;
oldDSN.DescribeSafetyConcerns = txtDescribeSafetyConcerns.Text;
oldDSN.OtherInfo = txtOtherInfo.Text;
oldDSN.Schedule_Monday = float.Parse(txtMonday.Text);
oldDSN.Schedule_Tuesday = float.Parse(txtTuesday.Text);
oldDSN.Schedule_Wednesday = float.Parse(txtWednesday.Text);
oldDSN.Schedule_Thursday = float.Parse(txtThursday.Text);
oldDSN.Schedule_Friday = float.Parse(txtFriday.Text);
oldDSN.Schedule_Saturday = float.Parse(txtSaturday.Text);
oldDSN.Schedule_Sunday = float.Parse(txtSunday.Text);
oldDSN.DateSaved = DateTime.Now;
oldDSN.SavedBy_UserID = currentEmployee.EmployeeID;
pfdcContext.SubmitChanges();
}
Response.Redirect("~/pages/updateTimesheet.aspx?action=update&ProvidedServiceId=" + int.Parse(Request["sp"]));
}
catch (Exception ex)
{
errorMessage.Text = "<b>Error updating an existing DSN record!</b><br /><br />" + ex.ToString();
warnings.Visible = true;
}
}
The only field that updates is oldDSN.DateSaved, everything else just stays the same. No errors or exceptions thrown or anything. Acts like it works, but doesn't. Also, when I hardcode values to be updated, the record updates just fine. Any ideas?
In your Page_Load (where you put the information from your datasource into the TextBoxes, etc) you need to wrap the databinding code in a If(Page.IsPostBack) block.
So your code should look something like this:
protected void Page_Load (object sender, EventArgs e)
{
if(!Page.IsPostBack)
{
// Whatever you use to load the data from the database into
// your server controls goes here
loadData(); // example
}
}
This is why you're not getting the updated information - your markup elements are being reloaded from the database before your Update code has a chance to run.
I have a GridView control which shows a list of all employees. When user selects any employee from this list, the record is shown on a Web Form with all input controls pre-filled with the values.
I want to know any good approach to do this. Should I bind all input controls to any SqlDataSource or should I re-populate all input controls by picking values from the DataSet.
First you add the select button on your GridView as:
<asp:ButtonField Text="Select" CommandName="ViewMe" ButtonType="Button" />
then you add the OnRowCommand="RowCommand" property on GridView to call this function when the button is clicked and on code behind the function:
protected void RowCommand(object sender, GridViewCommandEventArgs e)
{
// if the ViewMe command is fired
if (e.CommandName == "ViewMe")
{
// go to find the index on the grid view
int iTheIndexNow;
if (int.TryParse(e.CommandArgument.ToString(), out iTheIndexNow))
{
// Set and highlight the selected
TheGridView.SelectedIndex = iTheIndexNow;
// do we have the table data id ?
if (TheGridView.SelectedValue != null)
{
// now load the controls data using this id
LoadValuesFromDatabaseToControls(TheGridView.SelectedValue);
}
}
}
}
I prefer this way of command button because you can add more commands than the select, or edit, even the delete or copy... the just index change can be done for any reason (eg by changing page) and is also need again the select.
I use the subsonic 2 DAL for loading the data from the database. A sample code from my programs is:
void LoadValuesFromDatabaseToControls(string editID)
{
// Load it from database
AthUserMaiListName OneRow = new AthUserMaiListName(editID);
if (OneRow.IsNotExist)
{
// a custom control that show messages on top.
uResult.addMsg("Fail to load id " + editID, MsgType.error);
// close the view of the controls
dbViewPanel.Visible = false;
}
else // else we have the data and go for show them
{
// show this panel that contains the controls.
dbViewPanel.Visible = true;
// I keep my current edit id
lblID.Text = editID;
// just be sure that the select exist on DrowDownList
MyUtils.SelectDropDownList(ddlEventType, OneRow.CAddedFrom);
txtEmail.Text = OneRow.CEmail;
txtFirstName.Text = OneRow.CFirstName;
txtLastName.Text = OneRow.CLastName;
txtInsideTitle.Text = OneRow.CInsideTitle;
txtCompanyName.Text = OneRow.CCompanyName;
txtCreated.Text = DateTimeRender(OneRow.CreatedOn);
txtModified.Text = DateTimeRender(OneRow.ModifiedOn);
}
}
I used this code in my application-
A better approach would call to this mothod on gridview_select_index_change() event
private void PickValues(int SerialNum)
{
DataSet ds = new DataSet();
try
{
string Query = "SELECT * FROM tw_main WHERE sno = " + SerialNum;
ds = reuse.ReturnDataSet(Query, "Scheme");
//Add Scheme Code to new Session Variable
Session.Add("SerialNumber", ds.Tables[0].Rows[0]["sno"].ToString());
//Set Update Flag
TaskFlag = "UPDATE";
//Fill values of selected record on the Entry Form
if (ds.Tables[0].Rows[0]["schm_code"].ToString().Length > 0)
lblSchemeCode.Text = ds.Tables[0].Rows[0]["schm_code"].ToString();
ddlType.SelectedValue = ds.Tables[0].Rows[0]["schemetype"].ToString(); ddlDistrict.Text = ds.Tables[0].Rows[0]["dist_nm"].ToString(); ddlBlock.Text = ds.Tables[0].Rows[0]["block_nm"].ToString();
txtSchemeName.Text = ds.Tables[0].Rows[0]["schm_nm"].ToString();
txtPopulation2001.Text = ds.Tables[0].Rows[0]["population_2001"].ToString();
txtSupplySource.Text = ds.Tables[0].Rows[0]["supply_source"].ToString();
txtApprovalYear.Text = ds.Tables[0].Rows[0]["yr_approval"].ToString();
txtApprovalLetterNum.Text = ds.Tables[0].Rows[0]["approval_letter_num"].ToString();
txtApprovalAmount.Text = ds.Tables[0].Rows[0]["sch_apr_amt"].ToString();
txtWaitedLetterNum.Text = ds.Tables[0].Rows[0]["sch_waited_details"].ToString();
txtSchTransferLetterNum.Text = ds.Tables[0].Rows[0]["schm_trans_details"].ToString();
txtSchTransferDate.Text = ds.Tables[0].Rows[0]["schm_trans_date"].ToString();
txtOtherRemarks.Text = ds.Tables[0].Rows[0]["remarks"].ToString();
}
catch (Exception ex)
{
ScriptManager.RegisterClientScriptBlock(this.Page, this.Page.GetType(), "Warning", "alert('" + ex.Message.ToString() + "');",true);
}
finally
{
ds.Dispose();
gridSerialNo = 0;
}
}
EDIT
There might be better approach to do so but this works certainly fine.
The way I would perform this task since you want to create a data access layer is to create a class which has all the properties
Class:
public class tw_main
{
public string SchemeCode {get;set;}
}
DAL:
public class dal
{
public tw_main getSelectedValue(pass the parameters required by the method)
{
//your connection and query code
var twmain = new tw_main();
twmain.SchemaCode = ds.Tables[0].Rows[0]["schm_code"].ToString();
return twmain;
}
}
Web Page:
//depending upon where you add this a reference may need to be imported (using) to the namespace
var dalObj = new dal();
var tw = dalObj.getSelectedValue();
lblSchemeCode.Text = tw.SchemaCode;
I am trying to load session data in grid but no data is loaded my code is
protected void imageAddExtraField_Click(object sender, ImageClickEventArgs e)
{
List<ContentInfo> lstExtraFields = new List<ContentInfo>();
if (Session["ExtraField"] != null)
{
lstExtraFields = Session["ExtraField"] as List<ContentInfo>;
}
else
{
ContentInfo obj = new ContentInfo();
obj.ExtraFieldValue = ckEditorExtraField.Text;
obj.ExtraField = ddlExtraField.SelectedItem.ToString();
lstExtraFields.Add(obj);
gdvExtraField.DataSource = lstExtraFields;
gdvExtraField.DataBind();
Session["ExtraField"] = lstExtraFields;
}
}
i am using VS2008 any solution thanks.
I'm not sure if this is your intention, but when is something in the Session["ExtraFiled"], imageAddExtraField_Click does nothing with it. If you want to add more objects you might need to refactor a bit the code:
protected void imageAddExtraField_Click(object sender, ImageClickEventArgs e)
{
// check if nothing in the session, on success create a new list
if (Session["ExtraField"] == null)
{
Session["ExtraField"] = new List<ContentInfo>();
}
// get a reference to the list in session; previous code ensures is something
List<ContentInfo> lstExtraFields = (List<ContentInfo>)Session["ExtraField"];
ContentInfo obj = new ContentInfo();
obj.ExtraFieldValue = ckEditorExtraField.Text;
obj.ExtraField = ddlExtraField.SelectedItem.ToString();
lstExtraFields.Add(obj);
// bind the grid
gdvExtraField.DataSource = lstExtraFields;
gdvExtraField.DataBind();
// how do you bind when !PostBack?
}
}
Make sure the ExtraField is List object. 2. make sure the gridview is programmed to display the data (automatic column generation or manual column generation).