Can make the color separately? - c#

As you can see it is all red. I need the number to be red, but text to be black as shown on picture below. This is my code :
private void listBox2_SelectedIndexChanged(object sender, EventArgs e)
{
str1 = str;
str1 += listBox2.Text;
wassaw.Text = str1;
TextBox1.ForeColor = Color.Red;
switch (str1)
{
case "Привет1" :
TextBox1.Text = "" + Environment.NewLine + "1. привет " + Environment.NewLine + "2. привет " + Environment.NewLine + "3. привет ";
break;
case "Привет2" :
TextBox1.Text = "" + Environment.NewLine + "1. привет ";
break;
case "Приветф3" :
TextBox1.Text = "" + Environment.NewLine + "1 привет ";
break;
case "Приветы4" :
TextBox1.Text = "" + Environment.NewLine + "1 привет ";
break;
}
}

Not using a regular TextBox. The TextBox control just allows single color, single formatting text.
There are several options. You could create your own control, use external libraries, or you can use the RichTextBox which does allow formatting and coloring. With a little help, you can achieve what you want:
See this question how to do that: Color different parts of a RichTextBox string.
Another option would be to use a grid control, like the TableLayoutPanel and put the numbers and text in separate labels.

Related

Replace '\n' in multiple textbox at once

I have a window form application, inside this application, there have several textbox and want to replace the breakline and send out as email in one click. Since i have multiple textbox, instead of writing like this:
string text = textBox1.Text;
text = text.Replace("\n", "<br/>");
string text2 = textBox2.Text;
text2 = text2.Replace("\n", "<br/>");
...
string textBody ="<tr bgcolor = '#C39BD3'><td>Name</td><td>" + text + "</td></tr>" +"<tr bgcolor = '#C39BD3'><td>Age</td><td>" + text2 + "</td></tr>" + ...
is there any ways to replace the line in these textbox in one time?
I try to put in a loop:
for (int i = 1; i < 20; i++)
{TextBox txtbox = (TextBox)this.Controls.Find("textBox" + i, true)[0]; }
I stuck at here. Any suggestion?
Your Form is a Control, which has a property Controls This property "Gets the collection of controls contained within the control".
You can use Enumerable.OfType to filter this so you get only the TextBoxes.
Is there any ways to replace the line in these textbox in one time?
You'll need a foreach to replace the text:
var textBoxesToUpdate = this.Controls.OfType<TextBox>();
foreach (TextBox textBox in textBoxesToUpdate)
{
string proposedText = textBox.Text.Replace("\n", "<br/>");
textBox.Text = proposedText;
}
I also see this in your question
string textBody = "<tr bgcolor = '#C39BD3'><td>Name</td><td>" + text1 + "</td></tr>"
+ "<tr bgcolor = '#C39BD3'><td>Age</td><td>" + text2 + "</td></tr>"
+ ...
I don't know what you want with this. Consider to edit the question and change this.

Create a QR code from multiple textboxes and decode it back into the textboxes

I have created an application. This app contains the five textboxes id, name, surname, age and score.
When a user clicks the "okay button", these values are stores in an sql database.
Additionally, I want to store all of these information in an QR code. And when I decode it, the information should be shown in the textboxes respectively.
These are the references I am using so far.
using AForge.Video.DirectShow;
using Zen.Barcode;
using ZXing.QrCode;
using ZXing;
I can encode an ID number into a picture box, like so:
CodeQrBarcodeDraw qrcode = BarcodeDrawFactory.CodeQr;
pictureBox1.Image = qrcode.Draw(textBox1.Text, 50);
But I want all of the values in the textboxes to be storee in this QR code.
How can i do that?
The essence of the solution is, that you have to combine all the values from the textboxes into one string. To seperate them after decoding the QR code, you have to add a special character between the data values, that does not exist insinde the user input. After decoding the QR code, you can seperate the values by splitting the string at each occurance of the special character.
This is the quick and dirty way of doing that. If you want the QR code to be conformant to any specific format (like vcard), you have to reserach what it takes to compose the data for this format.
I expect your users cannot enter more than one line into the textboxes, so the newline character can be used as seperator character.
Encode all the information into one QR code.
var qrText = textBox1.Text + "\n" +
textBox2.Text + "\n" +
textBox3.Text + "\n" +
textBox4.Text + "\n" +
textBox5.Text;
pictureBox1.Image = qrcode.Draw(qrText, 50);
You can decode the QR code and assigning the data to the different textboxes again.
var bitmap = new Bitmap(pictureBox1.Image);
var lumianceSsource = new BitmapLuminanceSource(bitmap);
var binBitmap = new BinaryBitmap(new HybridBinarizer(source));
var reader = new MultiFormatReader();
Result result = null;
try
{
result = reader.Decode(binBitmap);
}
catch (Exception err)
{
// Handle the exceptions, in a way that fits to your application.
}
var resultDataArray = result.Text.Split(new char[] {'\n'});
// Only if there were 5 linebreaks to split the result string, it was a valid QR code.
if (resultDataArray.length == 5)
{
textBox1.Text = resultDataArray[0];
textBox2.Text = resultDataArray[1];
textBox3.Text = resultDataArray[2];
textBox4.Text = resultDataArray[3];
textBox5.Text = resultDataArray[4];
}
You can get this done by implementing below code :
"{" + '"' + "name" + '"' + ":" + '"' + txtName.Text + '"' + "," + '"' + "lname" + '"' + ":" + '"' + txtLname.Text + '"' + "," + '"' + "Roll" + '"' + ":" + '"' + txtRoll.Text + '"' + '"' + "class" + '"' + ":" + '"' + txtClass.Text + '"' + "}"
Result will be:
{"name":"Diljit","lname":"Dosanjh","Roll","2071","class":"BCA"}
Such that your QR scanner will recognize the data belong to its specific filed.

Is there a way to change the color of a specific word/string at run time of a WPF ListBox Item?

So all i want is if a specific word will be added in a listbox row/item, at run time, cause i am using a timer to add items at run time from my Database, i want that specific word/string to have a diferent color.
ie: All new item added that contains the string/word "Aproved", should be colored as green as soon as a new item its added to the WPF ListBox at run time.
private void dispatcherTimerMensagem_Tick(object sender, EventArgs e)
{
if (!(principalDB.testarConexãoDB()))
{
dispatcherTimerVendasFechadas.Stop();
dispatcherTimerMensagem.Stop();
LstMensagem.ItemsSource = null;
LbPbVendasFechadas.ItemsSource = null;
}
else
{
mensagem = principalDB.selectMessagemUsuario(null);
if (mensagem != string.Empty)
{
this.Activate();
LstMensagem.Opacity = 1;
LstMensagem.Items.Add(principalDB.mensagemRemetente + " (" + principalDB.mensagemData + ")" + ": " + mensagem);
voice.Voice = voice.GetVoices().Item(0);
myWorkerMensagem.WorkerReportsProgress = true;
myWorkerMensagem.WorkerSupportsCancellation = true;
myWorkerMensagem.RunWorkerAsync();
if (VisualTreeHelper.GetChildrenCount(LstMensagem) > 0)
{
Border border = (Border)VisualTreeHelper.GetChild(LstMensagem, 0);
ScrollViewer scrollViewer = (ScrollViewer)VisualTreeHelper.GetChild(border, 0);
scrollViewer.ScrollToBottom();
}
}
else
{
LstMensagem.Opacity = 0.5;
}
}
}
So the LstMensagem will recieve a new item at run time, from the variables declared, in this line of code:
LstMensagem.Items.Add(principalDB.mensagemRemetente + " (" + principalDB.mensagemData + ")" + ": " + mensagem);
If a specific word/string comes up, as ie "aproved" i want that string with a different text color,as example, brushed in green.
Use a TextBlock instead string. For entire item:
var text = principalDB.mensagemRemetente + " (" + principalDB.mensagemData + ")" + ": " + mensagem;
var tb = new TextBlock();
tb.Text = text;
if(text.Contains("aproved"))
tb.Foreground = Brushes.Green;
LstMensagem.Items.Add(tb);
For only part of the item, use the Inlines property to add different formatted texts:
var tb = new TextBlock();
tb.Inlines.Add(new Run { Foreground = Brushes.Green, Text =
principalDB.mensagemRemetente});
tb.Inlines.Add(" (" + principalDB.mensagemData + ")" + ": " + mensagem);
LstMensagem.Items.Add(tb);

C# How to check a Listbox for a string + object?

I'm trying to search for a certain number(object) in a listbox which comes together with a string in order to highlight it. In the following bit of code i override a ToString() method to contain all my objects.
public override string ToString()
{
string reservatiestring;
reservatiestring = "Kamer: " + roomNumber + "" + " Op datum: " + datum + " Aantal personen: " + personen.Count + " Naam: " + reservatienaam;
return reservatiestring;
}
Following this I add it to my listbox in the following bit of code:
listBox1.Items.Add(reservatie.ToString());
I now want to search for all the items in my listbox containing the same roomNumber object. To do this i tried the Contains() method with the text before it: "Kamer: " and the object which I'm looking for +comboBox1.SelectedItem. This however always fails and my code goes to the else option giving me the error message.
private void buttonSearch_Click(object sender, EventArgs e)
{
listBox1.SelectionMode = SelectionMode.MultiExtended;
Reservations reservaties = new Reservations();
reservaties.roomnumberstring = "Kamer: " + comboBox1.SelectedValue;
for (int i = listBox1.Items.Count - 1; i >= 0; i--)
{
if (listBox1.Items[i].ToString().ToLower().Contains(("Kamer: " + comboBox1.SelectedValue)))
{
listBox1.SetSelected(i, true);
}
else
{
MessageBox.Show("error");
}
Please note: All my roomNumber objects are stored in the combobox, so whenever i select for example roomNumber 3 in my combobox and hit search all the items in the listbox containing "Kamer: 3" should be selected.
The roomnumberstring is a option I tried which did not work unfortunately.
reservaties.roomnumberstring = "Kamer: " + comboBox1.SelectedValue;
Your override of the ToString method is wrong and won't modify anything. Try this :
public override string ToString(this string reservatiestring)
{
reservatiestring = "Kamer: " + roomNumber + "" + " Op datum: " + datum + " Aantal personen: " + personen.Count + " Naam: " + reservatienaam;
return reservatiestring;
}
I can see one thing that might make your code fail. you are comparing
.ToLower()
with "Kamer", where the "K" isn´t in lowercase

Click item in listbox and View details in multiline textbox

I would like to click on an item in a listbox and display the attributes that were passed into that listbox to a multiline textbox.
Below is the code I have written on form initialisation
public Form1()
{
InitializeComponent();
ReadFromFile.Read("sample.GED");
foreach (KeyValuePair<int, Individual> kvp in ReadFromFile.individuals)
{
listBox2.Items.Add("ID = " + kvp.Value.id + " Name = " + kvp.Value.name.givenName + " " + kvp.Value.name.surname + " DoB = " + kvp.Value.birth.date);
}
int testIndividual = 94;
string genderOut = "";
if (ReadFromFile.individuals[testIndividual].gender == "M")
{
genderOut = "MALE";
}
else if (ReadFromFile.individuals[testIndividual].gender == "F")
{
genderOut = "FEMALE";
}
try
{
textBox1.AppendText(
"Name = " + ReadFromFile.individuals[testIndividual].name.givenName + " "
+ ReadFromFile.individuals[testIndividual].name.surname
+ Environment.NewLine + "Gender = " + genderOut
+ Environment.NewLine + "Birth date = " + ReadFromFile.individuals[testIndividual].birth.date
+ Environment.NewLine + "Birth place = " + ReadFromFile.individuals[testIndividual].birth.place
+ Environment.NewLine + "Death date = " + ReadFromFile.individuals[testIndividual].death.date
+ Environment.NewLine + "Death place = " + ReadFromFile.individuals[testIndividual].death.place);
}
catch
{
MessageBox.Show("This individual doesnt exist");
}
}
}
I would like to add more so I can click on a listbox item and the details for that item will be shown in the textbox
I get the feeling I may have to override the ToString() method or regex it. Im still quite a novice programmer so go easy on me :) THANK YOU
You need to handle the SelectedIndexChanged event for your listbox.
One way to do this is to bring up Form1.cs[Design] and select the listbox. In the property grid (Alt+Enter) click the icon that looks like this:
Find the event SelectedIndexChanged and double click it. That will hook up an event handler for you in the auto generated Form1.cs.designer file.
Next, replace the code for your Form1 class with the following:
public partial class Form1 : Form
{
private Dictionary<int, Individual> _individuals;
public Form1()
{
InitializeComponent();
ReadFromFile.Read("sample.GED");
_individuals = ReadFromFile.individuals;
listBox1.DataSource = _individuals.Select(individual => individual.Value).ToList();
listBox1.DisplayMember = "name";
listBox1.ValueMember = "id";
}
private void listBox2_SelectedIndexChanged(object sender, EventArgs e)
{
textBox1.Clear();
var individual = listBox1.SelectedItem as Individual;
string genderOut = (individual.Gender == "M") ? "MALE" : "FEMALE";
var displayText
= String.Format("Name = {0} {1}\r\n" +
"Gender = {2}\r\n" +
"Birth date = {3}\r\n" +
"Birth place = {4}\r\n" +
"Death date = {5}\r\n" +
"Death place = {6}"
, individual.name.givenName
, individual.name.surname
, genderOut
, individual.birth.date
, individual.birth.place
, individual.death.date
, individual.death.place);
textBox1.AppendText(displayText);
}
}
A few notes about some of the things i've changed.
I've moved the code that was setting the textbox value into the SelectedIndexChanged event handler
I've refactored that code so that it's more readable by using the static String.Format method (all those Environment.NewLine repeats you had were messy).
I've setup the data for the list box using the DataSource property instead of your foreach loop.
Also, one thing you'll notice with this is that the list items in the listbox will not show the correct text. This is because you appear to be using some custom classes or structs for the name, birth and death of an Individual? To fix this, you need to add a new property to the Individual class like this:
public class Individual
{
// ... your code
public string DisplayName
{
get { return String.Format("{0} {1}), name.givenName, name.surname; }
}
// ... the rest of your code
}
Then you will need to change the line in my code above that looks like this:
listBox1.DisplayMember = "name";
to this:
listBox1.DisplayMember = "DisplayName";
Final note: You should probably be using "Upper Camel Case" for your property names. That means that they start with an upper case letter and then the first letter of each word is also upper case. For example, name.givenName should be Name.GivenName. This is a widely used convention.

Categories

Resources