Adding a new line when checking a checkbox - c#

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.

Related

Making text disappear while keep the default value

I am trying to make my text inside the box disappear when a new value is typed inside the box. I figured out how to make it disappear but my reset to default value no longer works. Which is the problem
I tried multiple += signs and if statements ideas but I am not sure how to make this work together.
private void BtnResetDefault_Click(object sender, EventArgs e)
{
txtElapsedTime.Text = "2";
txtCurrentAmount.Text = "25";
txtInitalAmount.Text = "100";
}
private void TxtInitalAmount_TextChanged(object sender, EventArgs e)
{
if (txtInitalAmount.Text.Contains("100") && txtElapsedTime.Text.Contains("2") && txtCurrentAmount.Text.Contains("25"))
{
txtElapsedTime.Text = "100";
txtCurrentAmount.Text = "2";
txtInitalAmount.Text = "25";
}
else if (txtCurrentAmount.Text != null)
{
txtInitalAmount.Text = "";
txtElapsedTime.Text = "";
txtCurrentAmount.Text = "";
}
}
I want to have when the user types in a value in the text box all 3 text boxes disappear and when the user clicks the reset to default button the default text comes back inside the text boxes. Instead when I hit reset to default it stays the same.
You can try to unsubscribe from event "txtInitalAmount.TextChanged", and then resubscribe to it.
private void BtnResetDefault_Click(object sender, EventArgs e)
{
txtElapsedTime.Text = "2";
txtCurrentAmount.Text = "25";
txtInitalAmount.TextChanged -= txtInitalAmount_TextChanged;
txtInitalAmount.Text = "100";
txtInitalAmount.TextChanged += txtInitalAmount_TextChanged;
}
private void txtInitalAmount_TextChanged(object sender, EventArgs e)
{
txtInitalAmount.TextChanged -= txtInitalAmount_TextChanged;
txtElapsedTime.Text = "";
txtCurrentAmount.Text = "";
txtInitalAmount.Text = "";
}

Custom search for AutoCompleteStringCollection

Is there anyway to change the search function for the AutoCompleteStringCollectionclass for the TextBox class? Right now, I have it on the default search function where the beginning letters of my suggestions match the letters of the user input? My suggestions come from a custom source.
You can make your own AutoComplete search - by using TextChange
Here is answer: C# winforms combobox dynamic autocomplete
Code:
string[] data = new string[] {
"Absecon","Abstracta","Abundantia","Academia","Acadiau","Acamas",
"Ackerman","Ackley","Ackworth","Acomita","Aconcagua","Acton","Acushnet",
"Acworth","Ada","Ada","Adair","Adairs","Adair","Adak","Adalberta","Adamkrafft",
"Adams"
};
public Form1()
{
InitializeComponent();
}
private void comboBox1_TextChanged(object sender, EventArgs e)
{
HandleTextChanged();
}
private void HandleTextChanged()
{
var txt = comboBox1.Text;
var list = from d in data
where d.ToUpper().StartsWith(comboBox1.Text.ToUpper())
select d;
if (list.Count() > 0)
{
comboBox1.DataSource = list.ToList();
//comboBox1.SelectedIndex = 0;
var sText = comboBox1.Items[0].ToString();
comboBox1.SelectionStart = txt.Length;
comboBox1.SelectionLength = sText.Length - txt.Length;
comboBox1.DroppedDown = true;
return;
}
else
{
comboBox1.DroppedDown = false;
comboBox1.SelectionStart = txt.Length;
}
}
private void comboBox1_KeyUp(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.Back)
{
int sStart = comboBox1.SelectionStart;
if (sStart > 0)
{
sStart--;
if (sStart == 0)
{
comboBox1.Text = "";
}
else
{
comboBox1.Text = comboBox1.Text.Substring(0, sStart);
}
}
e.Handled = true;
}
}

if user start typing in textbox value change to input else if user didn't type any thing value change to an specific string in C#

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! :)

Better approach in C# to search data on a third party web site

Here's my requirement. There is a public website which takes alphanumeric string as input and Retrieves data into a table element (via button click). The table element has couple of labels which gets populated with corresponding data. I need a tool/solution which can check if a particular string exists in the website's database. If so retrieve all the Ids of all the occurrences of that string. Looking at the "view source" of the website (No JavaScript used there), I noted the input element name and the button element name and with the help of existing samples I was able to get a working solution. Below is the code which works but I want to check if there is any better and faster approach. I know the below code has some issues like "infinite loop" issue and others. But I am basically looking at alternate solution which can work quickly for a million records.
namespace SearchWebSite
{
public partial class Form1 : Form
{
bool searched = false;
long i;
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
i = 1;
WebBrowser browser = new WebBrowser();
string target = "http://www.SomePublicWebsite.com";
browser.Navigate(target);
browser.DocumentCompleted += new WebBrowserDocumentCompletedEventHandler(XYZ);
}
private void XYZ(object sender, WebBrowserDocumentCompletedEventArgs e)
{
WebBrowser b = null;
if (searched == false)
{
b = (WebBrowser)sender;
b.Document.GetElementById("txtId").InnerText = "M" + i.ToString();
b.Document.GetElementById("btnSearch").InvokeMember("click");
searched = true;
}
if (b.ReadyState == WebBrowserReadyState.Complete)
{
if (b.Document.GetElementById("lblName") != null)
{
string IdNo = "M" + i.ToString();
string DateString = b.Document.GetElementById("lblDate").InnerHtml;
string NameString = b.Document.GetElementById("lblName").InnerHtml;
if (NameString != null && (NameString.Contains("XXXX") || NameString.Contains("xxxx")))
{
using (StreamWriter w = File.AppendText("log.txt"))
{
w.WriteLine("Id {0}, Date {1}, Name {2}", IdNo, DateString, NameString);
i = i + 1;
searched = false;
}
}
else
{
i = i + 1;
searched = false;
}
}
else
{
i = i + 1;
searched = false;
}
}
}
}
}
If the page after seach button clicked contains txtId and btnSearch controls than you can use this code snippet, this is not faster but the correct form I think.
public partial class Form1 : Form
{
bool searched = false;
long i = 1;
private string IdNo { get { return "M" + i.ToString(); } }
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
i = 1;
WebBrowser browser = new WebBrowser();
string target = "http://www.SomePublicWebsite.com";
browser.Navigate(target);
browser.DocumentCompleted += new WebBrowserDocumentCompletedEventHandler(XYZ);
}
private void XYZ(object sender, WebBrowserDocumentCompletedEventArgs e)
{
WebBrowser b = (WebBrowser)sender;
if (b.ReadyState == WebBrowserReadyState. Complete)
{
if (searched == false)
{
DoSearch(b); return;
}
if (b.Document.GetElementById("lblName") != null)
{
string DateString = b.Document.GetElementById("lblDate").InnerHtml;
string NameString = b.Document.GetElementById("lblName").InnerHtml;
if (NameString != null && (NameString.Contains("XXXX") || NameString.Contains("xxxx")))
using (StreamWriter w = File.AppendText("log.txt"))
w.WriteLine("Id {0}, Date {1}, Name {2}", IdNo, DateString, NameString);
}
i++;
DoSearch(b);
}
}
private void DoSearch(WebBrowser wb)
{
wb.Document.GetElementById("txtId").InnerText = IdNo;
wb.Document.GetElementById("btnSearch").InvokeMember("click");
searched = true;
}
}

How to prevent my textbox from clearing text on postback.

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.

Categories

Resources