I have a pretty interesting dilemma that is giving me a hurricane of a headache. I've seen a similar question asked here, but the user posted no code, so it was unresolved. This is a asp.net, sql server, and c# app.
In my application, I use JavaScript to display dummy data in a TextBox to entertain the user while a long process is running. (please note, this is a project, not a professional app).
The problem is, once the app is done executing, the app (I believe) refreshes the page and clears the TextBox. I want to prevent this from happening and continue to display the text after the program is completed.
My question is, where in the following code is the page being refreshed? How can I re-code it to prevent the text from being cleared?
I know there is no issue with the JavaScript or the .aspx page. I have not set or programmed any property to clear the text. If anyone could shed light on the issue, I would greatly appreciate it. If you need more code from me please let me know. I will be very active on this page until it is resolved. Thanks again!
public partial class SendOrders : System.Web.UI.Page
{
protected enum EDIType
{
Notes,
Details
}
protected static string NextBatchNum = "1";
protected static string FileNamePrefix = "";
protected static string OverBatchLimitStr = "Batch file limit has been reached. No more batches can be processed today.";
protected void Page_Load(object sender, EventArgs e)
{
Initialize();
}
protected void Page_PreRender(object sender, EventArgs e)
{ }
protected void btnExit_Click(object sender, EventArgs e)
{
System.Diagnostics.Process.GetCurrentProcess().Kill();
}
protected void Button_Click(object sender, EventArgs e)
{
PutFTPButton.Enabled = false;
Thread.Sleep(3000);
Button btn = (Button)sender;
KaplanFTP.BatchFiles bf = new KaplanFTP.BatchFiles();
KaplanFTP.Transmit transmit = new KaplanFTP.Transmit();
if (btn.ID == PutFTPButton.ID)
{
DirectoryInfo dir = new DirectoryInfo(#"C:\Kaplan");
FileInfo[] BatchFiles = bf.GetBatchFiles(dir);
bool result = transmit.UploadBatchFilesToFTP(BatchFiles);
if (!result)
{
ErrorLabel.Text += KaplanFTP.errorMsg;
return;
}
bf.InsertBatchDataIntoDatabase("CTL");
bf.InsertBatchDataIntoDatabase("HDR");
bf.InsertBatchDataIntoDatabase("DET");
bf.InsertBatchDataIntoDatabase("NTS");
List<FileInfo> allfiles = BatchFiles.ToList<FileInfo>();
allfiles.AddRange(dir.GetFiles("*.txt"));
bf.MoveFiles(allfiles);
foreach (string order in bf.OrdersSent)
{
OrdersSentDiv.Controls.Add(new LiteralControl(order + "<br />"));
}
btnExit.Visible = true;
OrdersSentDiv.Visible = true;
OrdersInfoDiv.Visible = false;
SuccessLabel.Visible = true;
NoBatchesToProcessLbl.Visible = true;
BatchesToProcessLbl.Visible = false;
PutFTPButton.Enabled = false;
BatchesCreatedLbl.Text = int.Parse(NextBatchNum).ToString();
Thread.Sleep(20000);
if (KaplanFTP.errorMsg.Length != 0)
{
ErrorLabel.Visible = false;
SuccessLabel.Visible = true;
ErrorLabel.Text = KaplanFTP.errorMsg;
}
}
}
private void Initialize()
{
KaplanFTP.BatchFiles bf = new KaplanFTP.BatchFiles();
if (!IsPostBack)
{
FileNamePrefix = bf.FileNamePrefix;
NextBatchNum = bf.NextBatchNum;
BatchesCreatedLbl.Text = (int.Parse(NextBatchNum) - 1).ToString();
if (bf.CheckLocalForNewBatch() == true)
{
NoBatchesToProcessLbl.Visible = false;
BatchesToProcessLbl.Visible = true;
if (int.Parse(NextBatchNum) >= 50)
{
ErrorLabel.Text += ErrorLabel.Text + OverBatchLimitStr;
ErrorLabel.Visible = true;
PutFTPButton.Enabled = false;
}
else
{
bf.ReadyFilesForTransmission();
ErrorLabel.Visible = false;
PutFTPButton.Enabled = true;
List<string[]> detStream = bf.GetBatchStream("DET");
List<string[]> hdrStream = bf.GetBatchStream("HDR");
OrdersInfoDiv.Visible = true;
DataTable dt = new DataTable();
dt.Columns.Add("ORDER NUMBER");
dt.Columns.Add("LINE NUMBER");
dt.Columns.Add("ITEM NUMBER/ISBN");
dt.Columns.Add("DESCRIPTION");
dt.Columns.Add("QUANTITY");
dt.Columns.Add("SHIPPING");
Dictionary<string, string> orderShip = new Dictionary<string, string>();
foreach (string[] hdrItems in hdrStream)
{
orderShip.Add(hdrItems[0], hdrItems[2]);
}
foreach (string[] detItems in detStream)
{
List<string> detLineList = new List<string>(detItems);
detLineList.Add(orderShip[detItems[0]]);
detLineList.RemoveAt(13);
detLineList.RemoveAt(12);
detLineList.RemoveAt(11);
detLineList.RemoveAt(10);
detLineList.RemoveAt(9);
detLineList.RemoveAt(8);
detLineList.RemoveAt(7);
detLineList.RemoveAt(4);
detLineList.RemoveAt(2);
detLineList[1] = detLineList[1].TrimStart('0');
detLineList[4] = detLineList[4].TrimStart('0');
dt.Rows.Add(detLineList.ToArray());
}
BatchDetails.DataSource = dt;
BatchDetails.DataBind();
}
}
else
{
NoBatchesToProcessLbl.Visible = true;
BatchesToProcessLbl.Visible = false;
PutFTPButton.Enabled = false;
}
}
}
}
Yes. You will have to determine the state of your calculation and populate the control inside Page_Load in the case where IsPostBack is true:
protected void Page_Load(object sender, EventArgs e) {
if (IsPostBack) {
// re-populate javascript-fill UI
} else {
}
Initialize();
}
You can probably also move Initialize() into the else clause as well.
Since you are handling the button click server side (I'm assuming the problem is happening once the user clicks the button?) there has to be a postback to handle it.
You could try putting your button and label into an updatepanel control - it uses AJAX to refresh its contents.
See this page for more information on updatepanels.
Related
When I click on a checkbox I want the next checkbox information to be displayed on a new line, I know how to do this with "\r\n" however when unchecking the box and rechecking the box, it adds a new line above the text moving the original text down by 1 line. https://imgur.com/a/IHDDG85
I've tried "\r\n" and Environment.NewLine
private void chkHamburger_CheckedChanged(object sender, EventArgs e)
{
if (chkHamburger.Checked == true)
{
txtHamburger.Enabled = true;
txtHamburger.Text = "";
txtHamburger.Focus();
txtOrder.Text += ("Hamburger");
}
else
{
txtHamburger.Enabled = false;
txtHamburger.Text = "0";
}
if (chkHamburger.Checked == false)
{
txtOrder.Text = txtOrder.Text.Replace("Hamburger", "");
}
}
private void chkCheeseBurger_CheckedChanged(object sender, EventArgs e)
{
if (chkCheeseBurger.Checked == true)
{
txtCheeseBurger.Enabled = true;
txtCheeseBurger.Text = "";
txtCheeseBurger.Focus();
txtOrder.Text += ("Cheese Burger");
}
else
{
txtCheeseBurger.Enabled = false;
txtCheeseBurger.Text = "0";
}
if (chkCheeseBurger.Checked == false)
{
txtOrder.Text = txtOrder.Text.Replace("Cheese Burger", "");
}
}
I want the text of a checkbox to be displayed on a new line but when rechecking the box a whitespace should not appear above it.
I suggest you to use a List<string> where you add or remove your orders. Then it is easy to rebuild the txtOrder data with a single line of code using string.Join
List<string> orders = new List<string>();
private void chkHamburger_CheckedChanged(object sender, EventArgs e)
{
txtHamburger.Enabled = chkHamburger.Checked;
if (chkHamburger.Checked)
{
txtHamburger.Text = "";
txtHamburger.Focus();
orders.Add("Hamburger");
}
else
{
txtHamburger.Text = "0";
orders.Remove("Hamburger");
}
UpdateOrders();
}
private void chkCheeseBurger_CheckedChanged(object sender, EventArgs e)
{
txtCheeseBurger.Enabled = chkCheeseBurger.Checked;
if (chkCheeseBurger.Checked)
{
txtCheeseBurger.Text = "";
txtCheeseBurger.Focus();
orders.Add("Cheese Burger");
}
else
{
txtCheeseBurger.Text = "0";
orders.Remove("Cheese Burger");
}
UpdateOrders();
}
private void UpdateOrders()
{
txtOrders.Text = string.Join(Environment.NewLine, orders);
}
The best way to do this is to have a routine that builds the contents of the text independent of what just happened -- this you could use join or a loop to create the text contents.
Make this a function and call it when the check boxes change. The function loops over all your items and adds them to the output with the formatting and totals etc.
I have a listview and created a textbox to search itmes in that list!
everything is ok about searching!
but problem is I want my search box to be like this:
at first Searchbox.Text="Search ..." and if user started typing in that searchbox change to that keyword! else(if) searchbox got empty Searchbox.Text change to "Search ..." again!
maybe it's a little complicated! but i tried 1-2 hours on it! and couldn't make it!
I have used Timers,checkboxchange event,booleans,...! but couldn't make it! :(
Please Help!
*my Searchbox name here is textbox1.
Some Codes I tested:
private void textBox1_TextChanged(object sender, EventArgs e)
{
string str = textBox1.Text;
/*
if (!keywordentered_bool)
{
textBox1.Text = "";
}
*/
if (str != "")
{
//Doing Search operations!
search_bool = true;
}
else
{//Doing Search operations!
search_bool = true;
// keywordentered_checkbox.Checked = true;
Searchtextbox_Timer.Interval = 100;
Searchtextbox_Timer.Enabled = true;
Searchtextbox_Timer.Tick += Searchtextbox_Timer_Tick;
//textBox2.Visible = false;
}
}
else
{
if (search_bool)
{
listView1.Items.Clear();
label1.Visible = false;
listView1.Items.AddRange(Originalplaylist_list.ToArray());
if (!search_bool)
{
listView1.Items[MusicLogindex_list[MusicLogindex_list.Count - 1]].ForeColor = Color.Cyan;
}
else if (search_bool)
{//Doing Search operations
search_bool = false;
Searchtextbox_Timer.Interval = 100;
Searchtextbox_Timer.Enabled = true;
Searchtextbox_Timer.Tick += Searchtextbox_Timer_Tick;
//textBox2.Visible = true;
// keywordentered_checkbox.Checked = false;
}
}
void Searchtextbox_Timer_Tick(object sender, EventArgs e)
{
if (!search_bool)
{
textBox2.Visible = true;
textBox2.Location = textBox1.Location;
//textBox1.Text = "Search ...";
//textBox1.ForeColor = Color.Gray;
//textBox1.Font = new Font(textBox1.Font, FontStyle.Italic);
}
else
{
textBox2.Visible = false;
// textBox1.Text = "";
// textBox1.ForeColor = Color.Black;
// textBox1.Font = new Font(textBox1.Font, FontStyle.Regular);
}
Searchtextbox_Timer.Enabled = false;
//throw new NotImplementedException();
}
This is just psuedocode but the concept is there and you need to implement the text change event for searching , you can do additional changes in event handler.
Textbox myTxtbx = new Textbox();
myTxtbx.Text = "Enter text here...";
myTxtbx.OnFocus += OnFocus.EventHandle(RemoveText);
myTxtbx.LoseFocus += LoseFocus.EventHandle(AddText);
public RemoveText(object sender, EventArgs e)
{
myTxtbx.Text = "";
}
public AddText(object sender, EventArgs e)
{
if(string.IsNullorEmpty(myTxtbx.Text))
myTxtbx.Text = "Enter text here...";
}
This is an example shows for a dynamic textbox control, you can add these events to your control and use the same code for make it work.
Or you can use this plugin
Visual Studio gallery plugin
Another plugin you can use for this purpose
Textbox with placeholder
Hope this helps.
thanks to #Frebin Francis my problem solved!
I downloaded the source code from this link TextBox With Placeholder
and added it to my project! then add it to my form and yeah! :)
I'm having a tiny issue here.. It's a little annoying.. I can't debug my application because of this..
My problem is.. When I try to open a new form automatically by code. It will not open other form. But when you click the button yourself on the form. It will open.. And I think this is a little weird.. Because it uses the same code...
Here is my button code that opens the new form(And it works great.):
private void button1_Click(object sender, EventArgs e)
{
label4.Text = "Login in... Please wait.";
Properties.Settings.Default.username = usernameText.Text;
if (checkBox1.Checked == true)
{
Properties.Settings.Default.check1 = true;
Properties.Settings.Default.password = passwordText.Text;
if (checkBox2.Checked == true)
{
Properties.Settings.Default.check2 = true;
}
}
Properties.Settings.Default.Save();
button1.Enabled = false;
checkBox1.Enabled = false;
checkBox2.Enabled = false;
startLoginWorker();
}
Here is the other code that opens it automatically:
private void loginForm_Load(object sender, EventArgs e)
{
String appDataFolder = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData).ToString();
String gpsPath = appDataFolder + "/GameProfileSaver";
label4.Text = "Checking files...";
if (!File.Exists(gpsPath + #"\ICSharpCode.SharpZipLib.dll") || !File.Exists(gpsPath + #"\ICSharpCode.SharpZipLib.dll"))
{
//startDownload("dll");
button1.Enabled = true;
}
else
{
button1.Enabled = true;
label4.Text = "File check complete. Ready for login.";
progressBar1.Value = 100;
}
if (checkBox2.Checked == true)
{
button1.PerformClick();
}
The "button1.PerformClick()" Just clicks the button by code right? Shouldn't be any difference....
And I have even tried to just put that code into that if statement.. Still nothing.
This is the code that gets run out of it all:
System.Threading.Thread t = new System.Threading.Thread(new System.Threading.ThreadStart(oppenMainForm));
t.SetApartmentState(ApartmentState.STA);
t.Start();
Openmainform:
private void oppenMainForm()
{
Application.Run(new Form1(usernameText.Text));
}
If anyone have any suggestions... Please help me... It's frustrating.
The Default is No Checkbox
When I run the program and Click the Yes Checkbox the program overflowed
private void checkEdit1_Click(object sender, EventArgs e)
{
checkEdit2.Checked = false;
textEdit1.Enabled = true;
answered = true;
optional = textEdit1.Text;
if (!checkEdit1.Checked)
{
checkEdit1.Checked = true;
checkEdit2.Checked = false;
textEdit1.Enabled = true;
optional = textEdit1.Text;
}
}
private void checkEdit2_Click(object sender, EventArgs e)
{
checkEdit1.Checked = false;
textEdit1.Enabled = false;
answered = false;
if (!checkEdit2.Checked)
{
checkEdit2.Checked = true;
checkEdit1.Checked = false;
textEdit1.Enabled = false;
answered = false;
}
}
What you think is the error ?
Instead of the Click event you should use the CheckedChanged event in this way:
checkEdit1.CheckedChenged += new EventHandler(checkEdit1_CheckedChanged);
checkEdit2.CheckedChenged += new EventHandler(checkEdit2_CheckedChanged);
private void checkEdit1_CheckedChanged(object sender, EventArgs e)
{
if(checkEdit1.Checked == checkEdit2.Checked)
checkEdit2.Checked = !checkEdit.Checked;
}
private void checkEdit2_CheckedChanged(object sender, EventArgs e)
{
if(checkEdit1.Checked == checkEdit2.Checked)
checkEdit2.Checked = !checkEdit.Checked;
}
But the best way in this case is to use a group of radio buttons.
Assuming that those methods are wired up to checkEdit1 and checkEdit2 I would advise that you don't make a change to checkEdit1 in checkEdit1_Click as it has already changed - only modify the state of the alternate.
However, when you modify the state of the other, unless you're careful, you're going to get called back. Eventually the computer gives up -- the overflow!
As mentioned in a comment by #Cyborgx37, radio buttons are the better UX choice here!
A possible solution, bind a single method to the OnClick to BOTH checkboxes:
private bool internallyUpdating = false;
private void CheckboxClick(object sender, EventArgs e)
{
if ( !internallyUpdating )
{
// Prevent subsequent changes
internallyUpdating = true;
// Exchange 'checked' state
if ( sender == checkEdit1 )
{
checkEdit2.Checked = !checkEdit2.Checked;
}
else // if (sender == checkEdit2)
{
checkEdit1.Checked = !checkEdit1.Checked;
}
// other logic here..
// restore 'on change' functionality.
internallyUpdating = false;
}
Im not very familiar with refactoring but I feel like I need to do some changes in this code...
I have 4 buttons in my app. Each one calls an method that receives data from an online xml and use this data to populate a listbox.
I kept myself repeating code for all those methods, although I see they differ sometimes.
Here is a little explanation of my logic:
The buttons btnA_Click and btnB_Click get the same data, but from differente years.
The same goes for the other 2 buttons. They get the same data(not the same as btnA
and btnB) but from different years too.
Buttons:
private void btnA_Click(object sender, RoutedEventArgs e)
{
string webService = #"xml from the web";
table.OpenReadAsync(new Uri(webService));
btnA.IsEnabled = false;
btnB.IsEnabled = false;
progressBar1.Visibility = System.Windows.Visibility.Visible;
}
private void btnB_Click(object sender, RoutedEventArgs e)
{
string webService = #"xml from the net";
table.OpenReadAsync(new Uri(webService));
btnA.IsEnabled = false;
btnB.IsEnabled = false;
progressBar1.Visibility = System.Windows.Visibility.Visible;
}
private void btnSTA_Click(object sender, RoutedEventArgs e)
{
string webService = #"xml from the web;
stats.OpenReadAsync(new Uri(webService));
btnSTA.IsEnabled = false;
btnSTB.IsEnabled = false;
progressBar3.Visibility = System.Windows.Visibility.Visible;
}
private void btnSTB_Click(object sender, RoutedEventArgs e)
{
string webService = #"xml from the web;
stats.OpenReadAsync(new Uri(webService));
btnSTA.IsEnabled = false;
btnSTB.IsEnabled = false;
progressBar3.Visibility = System.Windows.Visibility.Visible;
}
Methods:
void table_OpenReadCompleted(object sender, OpenReadCompletedEventArgs e)
{
if (e.Error == null && !e.Cancelled)
{
XElement xml = XElement.Load(e.Result);
var table = LINQ Statement...
listBox1.ItemsSource = table;
btnClassificacaoSerieA.IsEnabled = true;
btnClassificacaoSerieB.IsEnabled = true;
progressBar1.Visibility = System.Windows.Visibility.Collapsed;
}
}
void stats_OpenReadCompleted(object sender, OpenReadCompletedEventArgs e)
{
if (e.Error == null && !e.Cancelled)
{
XElement xml = XElement.Load(e.Result);
var stats = LINQ Statement...
listBox3.ItemsSource = stats;
btnSTA.IsEnabled = true;
btnSTB.IsEnabled = true;
progressBar3.Visibility = System.Windows.Visibility.Collapsed;
}
}
Im a little lost here. What could I do to make this code more Object Oriented?
Thx!
Your click events seem to mostly be the same... Make a sub that does that stuff and call the sub from the click event. See if you can put any differences in parameters.
Also your code for hiding / showing the progress bar and enable / disable of buttons is pretty much the same. stuff that in to a sub with a param that lets you say if you want to hide or show.