How can I do an ignore case search (C#) - c#

I'm trying to get an a case-insensitive search to work in C#. Currently my code is:
private void txtSearch_KeyPress_1(object sender, KeyPressEventArgs e)
{
if (e.KeyChar == (char)13)
{
if (!string.IsNullOrEmpty(txtSearch.Text))
{
var query = from o in App.Phonebook
where (o.PhoneNumber.Contains(txtSearch.Text) || o.Department.Contains(txtSearch.Text) || o.Name.Contains(txtSearch.Text) || o.Email.Contains(txtSearch.Text))
select o;
dataGridView.DataSource = query.ToList();
}
else
dataGridView.DataSource = phonebookBindingSource;
}
}
I have tried where (o.PhoneNumber.Contains(txtSearch.Text, StringComparison.InvariantCultureIgnoreCase), but I get the error "No overload for method 'Contains' takes 2 arguments." I don't want to do ToUpper() and ToLower().
Any advice would be appreciated.

There are various approaches.
private void txtSearch_KeyPress_1(object sender, KeyPressEventArgs e)
{
if (e.KeyChar == (char)13)
{
if (!string.IsNullOrEmpty(txtSearch.Text))
{
var query = from o in App.Phonebook
where ((o.PhoneNumber.IndexOf(txtSearch.Text, StringComparison.InvariantCultureIgnoreCase) >= 0) || (o.Department.IndexOf(txtSearch.Text, StringComparison.InvariantCultureIgnoreCase) >= 0) || (o.Name.IndexOf(txtSearch.Text, StringComparison.InvariantCultureIgnoreCase) >= 0) || (o.Email.IndexOf(txtSearch.Text, StringComparison.InvariantCultureIgnoreCase) >= 0))
select o;
dataGridView.DataSource = query.ToList();
}
else
dataGridView.DataSource = phonebookBindingSource;
}
}
Alternative you could write an extension method:
public static class MyExtensions
{
public static bool ContainsInsensitive(this String str, string txt)
{
return str.IndexOf(txt, StringComparison.InvariantCultureIgnoreCase) >= 0;
}
}
private void txtSearch_KeyPress_1(object sender, KeyPressEventArgs e)
{
if (e.KeyChar == (char)13)
{
if (!string.IsNullOrEmpty(txtSearch.Text))
{
var query = from o in App.Phonebook
where (o.PhoneNumber.ContainsInsensitive(txtSearch.Text) || o.Department.ContainsInsensitive(txtSearch.Text) || o.Name.ContainsInsensitive(txtSearch.Text) || o.Email.ContainsInsensitive(txtSearch.Text))
select o;
dataGridView.DataSource = query.ToList();
}
else
dataGridView.DataSource = phonebookBindingSource;
}
}

Related

Change row color in datagridview

I know it's already been written about.
Everything looks very good. But when I move to the right to see the rest of the columns, the rows in DataDridView start blinking very much. I can't solve this.
private void registersDataGridView_CellFormatting(object sender, DataGridViewCellFormattingEventArgs e)
{
DataGridViewRow rowDataGridView = null;
string dataPropertyName;
dataPropertyName = this.registersDataGridView.Columns[e.ColumnIndex].DataPropertyName;
int isApprovedColumnIndex = this.registersDataGridView.Columns[isApprovedColumnName].Index;
int isCancelledColumnIndex = this.registersDataGridView.Columns[isCancelledColumnName].Index;
bool theColorHasBeenSet = false;
if (e.RowIndex >= 0 && e.RowIndex != btregisterDgvRowIndex)
{
rowDataGridView = this.registersDataGridView.Rows[e.RowIndex];
if (this.registersDataGridView.Columns[isCancelledColumnIndex].DataPropertyName == "IsCancelled")
{
if (rowDataGridView.Cells[isCancelledColumnIndex].Value != null && rowDataGridView.Cells[isCancelledColumnIndex].Value.ToString() == "Tak")
{
if (rowDataGridView.DefaultCellStyle.BackColor != Color.PaleVioletRed)
{
rowDataGridView.DefaultCellStyle.BackColor = Color.PaleVioletRed;
}
theColorHasBeenSet = true;
}
else
{
if (rowDataGridView.DefaultCellStyle.BackColor != Color.Ivory)
{
rowDataGridView.DefaultCellStyle.BackColor = Color.Ivory;
}
}
btregisterDgvRowIndex = e.RowIndex;
}
if (this.registersDataGridView.Columns[isApprovedColumnIndex].DataPropertyName == "IsApproved")
{
if (!theColorHasBeenSet)
{
if (rowDataGridView.Cells[isApprovedColumnName].Value != null && rowDataGridView.Cells[isApprovedColumnName].Value.ToString() == "-")
{
if (rowDataGridView.DefaultCellStyle.BackColor != Color.LightGray)
{
rowDataGridView.DefaultCellStyle.BackColor = Color.LightGray;
}
theColorHasBeenSet = true;
}
else if (rowDataGridView.Cells[isApprovedColumnName].Value != null && rowDataGridView.Cells[isApprovedColumnName].Value.ToString() == "Nie")
{
if (rowDataGridView.DefaultCellStyle.BackColor != Color.PaleVioletRed)
{
rowDataGridView.DefaultCellStyle.BackColor = Color.PaleVioletRed;
}
theColorHasBeenSet = true;
}
else
{
if (rowDataGridView.DefaultCellStyle.BackColor != Color.Ivory)
{
rowDataGridView.DefaultCellStyle.BackColor = Color.Ivory;
}
}
btregisterDgvRowIndex = e.RowIndex;
}
}
}
}
else
{
if (rowDataGridView.DefaultCellStyle.BackColor != Color.Ivory)
{
rowDataGridView.DefaultCellStyle.BackColor = Color.Ivory;
}
}
You're not setting the theColorHasBeenSet here which might cause it to change between Ivory and the next color on your list.
Your code seems to verbose to me, try the following
private void dataGridView1_CellFormatting(object sender, DataGridViewCellFormattingEventArgs e)
{
if (e.RowIndex < 0)
return;
var rowDataGridView = this.registersDataGridView.Rows[e.RowIndex];
Color GetBackgroundColor()
{
var isApprovedColumnIndex = this.registersDataGridView.Columns[isApprovedColumnName].Index;
var isCancelledColumnIndex = this.registersDataGridView.Columns[isCancelledColumnName].Index;
if (this.registersDataGridView.Columns[isCancelledColumnIndex].DataPropertyName == "IsCancelled")
{
var strValue = Convert.ToString(rowDataGridView.Cells[isCancelledColumnIndex].Value);
if (strValue == "Tak")
return Color.PaleVioletRed;
}
if (this.registersDataGridView.Columns[isApprovedColumnIndex].DataPropertyName == "IsApproved")
{
var strValue = Convert.ToString(rowDataGridView.Cells[isApprovedColumnIndex].Value);
if (strValue == "-")
return Color.LightGray;
if (strValue == "Nie")
return Color.PaleVioletRed;
}
return Color.Ivory;
}
rowDataGridView.DefaultCellStyle.BackColor = GetBackgroundColor();
}

How to create complex filter for DataGrid WPF

I want to create filrer for 4 fields. But I get too many code.
I need filter when just one field choosen or a few (2,3 or 4) fields at the same time. How to create logic for it?
My ugly code:
void ViewSource_Filter(object sender, FilterEventArgs e)
{
if (e.Item is Event evnt)
{
bool selectedModel = filterEventsControl.ComboBoxModels.SelectedIndex != 0 && filterEventsControl.ComboBoxModels.SelectedItem != null;
bool selectedIp = filterEventsControl.ComboBoxIPs.SelectedIndex != 0 && filterEventsControl.ComboBoxIPs.SelectedItem != null;
bool selectedParameter = filterEventsControl.ComboBoxParameters.SelectedIndex != 0 && filterEventsControl.ComboBoxParameters.SelectedItem != null;
bool selectedStatus = filterEventsControl.ComboBoxStatus.SelectedIndex != 0 && filterEventsControl.ComboBoxStatus.SelectedItem != null;
if (selectedModel && !selectedIp && !selectedParameter && !selectedStatus)
{
var model = filterEventsControl.ComboBoxModels.SelectedItem.ToString();
if (evnt.DeviceName == model)
{
e.Accepted = true;
}
else
{
e.Accepted = false;
}
}
else if (selectedModel && selectedIp && !selectedParameter && !selectedStatus)
{
var model = filterEventsControl.ComboBoxModels.SelectedItem.ToString();
var ip = filterEventsControl.ComboBoxIPs.SelectedItem.ToString();
if (evnt.DeviceName == model && evnt.Ip == ip)
{
e.Accepted = true;
}
else
{
e.Accepted = false;
}
}
...
else
{
e.Accepted = true;
}
}
}
It can be something like this:
bool FilterByName(Event evnt)
{
var model = filterEventsControl.ComboBoxModels.SelectedItem?.ToString();
return evnt.DeviceName == model;
}
bool FilterByIp(Event evnt)
{
var ip = filterEventsControl.ComboBoxIPs.SelectedItem?.ToString();
return evnt.Ip == ip;
}
void ViewSource_Filter(object sender, FilterEventArgs e)
{
...
bool res = true;
if (selectedModel)
res = res && FilterByName();
if (selectedIp)
res = res && FilterByIp();
...
}

How to save data from textboxes by linking comboboxes and checkboxes into richtextbox c#

I am creating a scheduler where data I entered below on two textboxes have to appear according to the Day or week and Time values. I've tried with the following code, but didn't work.
private void btnEnterData_click(object sender, System.EventArgs e)
{
if (((cmbDayWeek.SelectedIndex == 0) && (chb910.Checked == true)))
{
rtb1.Text = (tbxMedNumAppn.Text + tbxDocSpecAppn.Text);
}
else if (((cmbDayWeek.SelectedIndex == 0) && (chb1011.Checked == true)))
{
rtb7.Text = (tbxMedNumAppn.Text + tbxDocSpecAppn.Text);
}
return;
//and codes all the way down
}
private void btnSavePatient_Click(object sender, EventArgs e)
{
if (((cmbDayWeek.SelectedIndex == 0) && (chb910.Checked == true)))
{
rtb1.Show();
}
if (((cmbDayWeek.SelectedIndex == 0) && (chb1011.Checked == true)))
{
rtb2.Show();
}
// codes all the way down
}
P.S. I'm assuming that I have to use If/Else statement, but I can't get the logic fully :(
Image of the scheduler:

Can't get backgoundworker to work

I can't get background worker to work. This is my first time using it so I don't know if I have done something wrong. Here's my code:
int cardcount = 0;
string lev = "";
string att = "";
string atk = "";
string def = "";
string ctp = "";
string id = "";
void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
{
if (folderBrowserDialog1.ShowDialog() == System.Windows.Forms.DialogResult.OK)
{
string folder = folderBrowserDialog1.SelectedPath;
DirectoryInfo dinfo = new DirectoryInfo(folderBrowserDialog1.SelectedPath);
FileInfo[] Files = dinfo.GetFiles("*.jpg");
int count = Files.Length;
int current = 0;
foreach (FileInfo file in Files)
{
string path = Path.GetFileNameWithoutExtension(file.Name);
int cardid = Convert.ToInt32(path);
if (Program.CardData.ContainsKey(cardid))
{
DevPro_CardManager.cardmaker.IMG = LoadBitmap(folderBrowserDialog1.SelectedPath + "//" + file.Name);
id = Program.CardData[cardid].Id.ToString();
lev = Program.CardData[cardid].Level.ToString();
att = Program.CardData[cardid].Attribute.ToString();
if (att == "1")
{
att = "earth";
}
else if (att == "2")
{
att = "water";
}
else if (att == "4")
{
att = "fire";
}
else if (att == "8")
{
att = "wind";
}
else if (att == "16")
{
att = "light";
}
else if (att == "32")
{
att = "dark";
}
else if (att == "64")
{
att = "divine";
}
if (Program.CardData[cardid].Atk.ToString() == "-2")
{
atk = "????";
}
else
{
atk = Program.CardData[cardid].Atk.ToString();
}
if (Program.CardData[cardid].Def.ToString() == "-2")
{
def = "????";
}
else
{
def = Program.CardData[cardid].Def.ToString();
}
ctp = Program.CardData[cardid].Type.ToString();
if (ctp == "2" || ctp == "130" || ctp == "65538" || ctp == "131074" || ctp == "262146" || ctp == "524290")
{
ctp = "spell";
}
else if (ctp == "4" || ctp == "1048580" || ctp == "131076")
{
ctp = "trap";
}
else if (ctp == "129" || ctp == "161")
{
ctp = "ritual";
}
else if (ctp == "65" || ctp == "97")
{
ctp = "fusion";
}
else if (ctp == "8193" || ctp == "8225" || ctp == "12321")
{
ctp = "synchro";
}
else if (ctp == "8388609" || ctp == "8388641")
{
ctp = "xyz";
}
else if (ctp == "33" || ctp == "545" || ctp == "1057" || ctp == "2081" || ctp == "4129" || ctp == "4194337")
{
ctp = "effect";
}
else if (ctp == "17" || ctp == "4113")
{
ctp = "normal";
}
else if (ctp == "16401")
{
ctp = "token";
}
cardcount = cardcount + 1;
backgroundWorker1.ReportProgress((current * 100) / count);
}
}
}
}
void backgroundWorker1_ProgressChanged(object sender, ProgressChangedEventArgs e)
{
// The progress percentage is a property of e
progressBar1.Value = e.ProgressPercentage;
label8.Text = cardcount.ToString();
comboBox2.SelectedItem = lev;
comboBox1.SelectedItem = att;
textBox2.Text = atk;
textBox1.Text = def;
comboBox3.SelectedItem = ctp;
GenerateCard();
ImageResizer.CropImage(361, 523, pictureBox1.Image, #"anime cards\" + Path.GetFileName(id));
}
And the code for the button that launches it:
private void button5_Click(object sender, EventArgs e)
{
backgroundWorker1.RunWorkerAsync();
}
Please help or say if I'm doing something wrong, thanks.
If you really need to call ShowDialog from the background thread you will need to marshal the call to the foreground thread using Invoke. Here's an example of how you might do this:
public partial class Form1 : Form
{
private delegate DialogResult ShowFolderBrowser();
public Form1()
{
InitializeComponent();
}
private DialogResult ShowFolderBrowserDialog()
{
return this.folderBrowserDialog1.ShowDialog();
}
private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
{
if ((DialogResult)this.Invoke(this.ShowFolderBrowserDialog) == DialogResult.OK)
{
// ...
}
}
private void button1_Click(object sender, EventArgs e)
{
this.backgroundWorker1.RunWorkerAsync();
}
}
However, I would recommend that you rethink your design somewhat. You never explained why you're using a BackgroundWorker in the first place. Why can't you start up the BackgroundWorker after you've shown the folder browser dialog? Like this:
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
{
string folder = e.Argument as string;
// ...
}
private void button1_Click(object sender, EventArgs e)
{
if (this.folderBrowserDialog1.ShowDialog() == DialogResult.OK)
{
string folder = this.folderBrowserDialog1.SelectedPath;
this.backgroundWorker1.RunWorkerAsync(folder);
}
}
}
The most important detail you overlooked is that you have to do something reasonable when the worker threw an exception. At a minimum, you'll have to report it in your RunWorkerCompleted event handler:
private void backgroundWorker1_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e) {
if (e.Error != null) {
MessageBox.Show(e.Error.ToString());
}
else {
// etc..
}
}
You will now also discover the problem in your code, you cannot use OpenFileDialog on a worker thread. Display it on the UI thread instead and then start the worker, passing the selection.
And yes, this is different from what you are used to, you expect the debugger to tell you about unhandled exceptions. That doesn't work the same way when a try/catch is wrapping code, they are built into the BackgroundWorker class. You can get the debugger to stop at such an invisible exception with Debug + Exceptions, tick the Thrown checkbox for CLR exceptions. This is not otherwise a good reason to skip the e.Error check in the event handler.

Masked TextBox with decimal numbers

In my window application I need masked textbox which accept real decmal numbers.
eg.
1) 1.56
2) 22.34
3) 123.34
4) 12312.34
This all value should be valid.
Can anyone tell me how can I do this?
And ya if anyone have better solution for real decimal numbers, instead of this masked TextBox
than I love to see it.
Thanks...
Instead of using a MaskedTextbox, consider using NumericUpDown instead. It supports System.Decimal numbers which supports most real-set numbers you should be caring about.
The NumericUpDown.DecimalPlaces property supports up to 99 decimal places.
Use a custom control like this one (modify it to fulfill your needs):
using System;
using System.ComponentModel;
using System.Text;
using System.Windows.Forms;
using System.Drawing;
namespace CustomControls
{
public enum PasteRejectReasons
{
Unknown = 0,
NoData,
InvalidCharacter,
Accepted
}
public class DecimalTextBox : TextBox
{
public const int WM_PASTE = 0x0302;
public event EventHandler<KeyRejectedEventArgs> KeyRejected;
public event EventHandler<PasteEventArgs> PasteRejected;
private bool _DecimalSeparator = false;
private int _Precision;
public new HorizontalAlignment TextAlign
{
get { return base.TextAlign; }
set { base.TextAlign = value; }
}
public int Precision
{
get { return _Precision; }
set { _Precision = value; }
}
public DecimalTextBox()
{
TextAlign = HorizontalAlignment.Right;
Precision = 3;
}
protected override void OnGotFocus(EventArgs e)
{
SelectAll();
base.OnGotFocus(e);
}
protected override void OnKeyDown(KeyEventArgs e)
{
bool validate = true;
if (Text.Contains(".") || Text.Contains(","))
{
int indexSep;
string[] split;
string partiDecimal = "";
if (Text.Contains("."))
indexSep = Text.IndexOf('.');
else
indexSep = Text.IndexOf(',');
split = Text.Split(new char[] { ',', '.' });
partiDecimal += split[1];
if (partiDecimal.Length >= Precision)
if (SelectionStart > Text.Length - (partiDecimal.Length + 1))
validate = false;
}
bool result = true;
bool validateKeys = (e.KeyCode == Keys.Enter);
bool numericKeys = (
((e.KeyCode >= Keys.D0 && e.KeyCode <= Keys.D9) ||
(e.KeyCode >= Keys.NumPad0 && e.KeyCode <= Keys.NumPad9))
&& e.Modifiers != Keys.Shift
&& validate);
bool ctrlA = e.KeyCode == Keys.A && e.Modifiers == Keys.Control;
bool editKeys = (
(e.KeyCode == Keys.Z && e.Modifiers == Keys.Control) ||
(e.KeyCode == Keys.X && e.Modifiers == Keys.Control) ||
(e.KeyCode == Keys.C && e.Modifiers == Keys.Control) ||
(e.KeyCode == Keys.V && e.Modifiers == Keys.Control) ||
e.KeyCode == Keys.Delete ||
e.KeyCode == Keys.Back);
bool navigationKeys = (
e.KeyCode == Keys.Up ||
e.KeyCode == Keys.Right ||
e.KeyCode == Keys.Down ||
e.KeyCode == Keys.Left ||
e.KeyCode == Keys.Home ||
e.KeyCode == Keys.End);
bool decimalSeparator = ((
e.KeyCode == Keys.Decimal ||
e.KeyValue == 190 ||
e.KeyValue == 188)&&
TextLength != 0 &&
SelectionLength == 0);
if (decimalSeparator)
{
if (!_DecimalSeparator)
_DecimalSeparator = true;
else
decimalSeparator = false;
}
if (!(numericKeys || editKeys || navigationKeys || decimalSeparator || validateKeys))
{
if (ctrlA)
SelectAll();
result = false;
}
if (!result)
{
e.SuppressKeyPress = true;
e.Handled = true;
if (!ctrlA)
OnKeyRejected(new KeyRejectedEventArgs(e.KeyCode));
}
else
base.OnKeyDown(e);
}
protected override void OnKeyPress(KeyPressEventArgs e)
{
if (e.KeyChar == ';' || e.KeyChar == '?')
{
if (!(Text.Contains(",") || Text.Contains(".")))
_DecimalSeparator = false;
e.Handled = true;
}
}
protected override void OnTextChanged(EventArgs e)
{
bool invalid = false;
int i = 0;
foreach (char c in Text) // Check for any non digit characters.
{
if (!(char.IsDigit(c) || c == ',' || c == '.'))
{
invalid = true;
break;
}
if (c == ',' || c == '.')
i++;
}
if (i == 0)
_DecimalSeparator = false;
else if (i > 1)
invalid = true;
if (invalid)
{
Text = "";
return;
}
if (Text.Contains(".") || Text.Contains(","))
{
string charSep = "";
string[] split;
string partiEntier = "";
if (Text.Contains("."))
charSep = ".";
else
charSep = ",";
split = Text.Split(new char[] { ',', '.' });
partiEntier += split[0];
if (partiEntier == "")
Text = "0" + charSep + split[1];
}
base.OnTextChanged(e);
}
protected override void WndProc(ref Message m)
{
if (m.Msg == WM_PASTE)
{
PasteEventArgs e = CheckPasteValid();
if (e.RejectReason != PasteRejectReasons.Accepted)
{
m.Result = IntPtr.Zero;
OnPasteRejected(e);
return;
}
}
base.WndProc(ref m);
}
private PasteEventArgs CheckPasteValid()
{
PasteRejectReasons rejectReason = PasteRejectReasons.Accepted;
string originalText = Text;
string clipboardText = string.Empty;
string textResult = string.Empty;
try
{
clipboardText = Clipboard.GetText(TextDataFormat.Text);
if (clipboardText.Length > 0)
{
textResult = (
Text.Remove(SelectionStart, SelectionLength).Insert(SelectionStart, clipboardText));
foreach (char c in clipboardText)
{
if (!char.IsDigit(c))
{
rejectReason = PasteRejectReasons.InvalidCharacter;
break;
}
}
}
else
rejectReason = PasteRejectReasons.NoData;
}
catch
{
rejectReason = PasteRejectReasons.Unknown;
}
return new PasteEventArgs(originalText, clipboardText, textResult, rejectReason);
}
protected virtual void OnKeyRejected(KeyRejectedEventArgs e)
{
EventHandler<KeyRejectedEventArgs> handler = KeyRejected;
if (handler != null)
handler(this, e);
}
protected virtual void OnPasteRejected(PasteEventArgs e)
{
EventHandler<PasteEventArgs> handler = PasteRejected;
if (handler != null)
handler(this, e);
}
}
}

Categories