C#, form app. Calling a method in a button click - c#

My code is a program that generates a random number between 1-4 in button1_click, then passes it to GetQuestion and selects a random question based on what the random number was. It should then check the textbox1 for input on what the answer is, and check if it's correct in the GetAnswer function. Problem is, i can't seem to figure out how to pass the questionNum to GetAnswer without passing it as a parameter. If i tried to pass it as a parameter, my button2_click what calls the GetAnswer, wouldn't work since the method call would need a parameter and i don't know how to make it work. Please help!
public struct QuestionAnswer
{
public string question;
public string answer;
}
public QuestionAnswer[] answers = new QuestionAnswer[3];
private int GetQuestion(int questionNum)
{
QuestionAnswer q1;
q1.question = "What is a salmon?";
q1.answer = "Fish";
QuestionAnswer q2;
q2.question = "How many meters is a kilometer?";
q2.answer = "1000";
QuestionAnswer q3;
q3.question = "How much is 1 + 1?";
q3.answer = "2";
answers[0] = q1;
answers[1] = q2;
answers[2] = q3;
label1.Visible = true;
if (questionNum == 1)
{
label1.Text = q1.question;
}
else if (questionNum == 2)
{
label1.Text = q2.question;
}
else
{
label1.Text = q3.question;
}
return questionNum;
}
private void GetAnswer()
{
label2.Visible = true;
string answer = textBox1.Text;
if (answer == answers[0].answer && questionNum == 1 || answer == answers[1].answer && questionNum == 2 || answer == answers[2].answer && questionNum == 3)
{
label2.Text = "Correct!";
}
else
{
label2.Text = "Wrong!";
}
}
private void button2_Click(object sender, EventArgs e)
{
GetAnswer();
}
private void button1_Click(object sender, EventArgs e)
{
label2.Visible = false;
Random rnd = new Random();
int questionNum = rnd.Next(1, 4);
GetQuestion(questionNum);
}
}

You simply need to use a field, like you have for answers to keep track of your current question.
Now, I've refactored your code to see how you might go about writing this.
private Random _rnd = new Random();
private int _questionIndex = 0;
public QuestionAnswer[] _answers = new QuestionAnswer[]
{
new QuestionAnswer() { Question = "What is a salmon?", Answer = "Fish" },
new QuestionAnswer() { Question = "How many meters is a kilometer?", Answer = "1000" },
new QuestionAnswer() { Question = "How much is 1 + 1?", Answer = "2" },
};
private void button2_Click(object sender, EventArgs e)
{
label2.Visible = true;
string answer = textBox1.Text;
label2.Text =
answer == _answers[_questionIndex].Answer
? "Correct!"
: "Wrong!";
}
private void button1_Click(object sender, EventArgs e)
{
label2.Visible = false;
label1.Visible = true;
_questionIndex = _rnd.Next(0, _answers.Length);
label1.Text = _answers[_questionIndex].Question;
}

you could make use of tag property, if you don't want to use global variable
public struct QuestionAnswer
{
public string question;
public string answer;
}
private QuestionAnswer[] answers = new QuestionAnswer[3];
private int GetQuestion(int questionNum)
{
QuestionAnswer q1;
q1.question = "What is a salmon?";
q1.answer = "Fish";
QuestionAnswer q2;
q2.question = "How many meters is a kilometer?";
q2.answer = "1000";
QuestionAnswer q3;
q3.question = "How much is 1 + 1?";
q3.answer = "2";
answers[0] = q1;
answers[1] = q2;
answers[2] = q3;
label1.Visible = true;
if (questionNum == 1)
{
label1.Text = q1.question;
}
else if (questionNum == 2)
{
label1.Text = q2.question;
}
else
{
label1.Text = q3.question;
}
return questionNum;
}
private void GetAnswer(int questionNum)
{
label2.Visible = true;
string answer = textBox1.Text;
if (answer == answers[0].answer && questionNum == 1 || answer == answers[1].answer && questionNum == 2 || answer == answers[2].answer && questionNum == 3)
{
label2.Text = "Correct!";
}
else
{
label2.Text = "Wrong!";
}
}
private void button2_Click(object sender, EventArgs e)
{
if(button1.Tag != null && int.TryParse(button1.Tag?.ToString(),out int result))
GetAnswer((int)button1.Tag);
}
private void button1_Click(object sender, EventArgs e)
{
label2.Visible = false;
Random rnd = new Random();
int questionNum = rnd.Next(1, 4);
button1.Tag = questionNum;
GetQuestion(questionNum);
}

Related

How can I make the strings from the list translate to each other?

I have two lists with different strings. One list contains strings in one language and the other lists contains their translation. I've been stuck on this for ages(even tried using Dictionary<> but then had a problem with the random part)
How can I make the strings match each other to make a memory word based game?
Random random = new Random();
List<string> EngBasicPhrases = new List<string>()
{
"Hello", "How are you?", "Hot", "Thank you", "Welcome",
"Let's go", "My name is...", "Cold", "Good luck",
"Congratulations", "Bless you","I forgot","Sorry","I'm fine",
"It's no problem","Don't worry","Here it is","What?","Of course",
"Boy","Girl","Man","Woman","Friend","Almost","Late"
};
List<string> FrBasicPhrases = new List<string>()
{
"Salut","Ca va?","Chaud", "Merci", "Bienvenu", "Allons-y","Je m'appelle","Du froid",
"Bonne chance","Felicitations","A vos souhaits","J'ai oublie","Desole","Je vais bien",
"Ce n'est pas grave","Ne t'en fais pas","Voila","Comment?","Bien sur","Un garcon","Une fille",
"Un home","Une femme","Un ami","Presque","En retard"
};
Button firstClicked, secondClicked;
public Game()
{
InitializeComponent();
AssignWordsToSquares();
EngBasicPhrases.AddRange(FrBasicPhrases);
}
public void AssignWordsToSquares()
{
Button button1 = button2;
int randomNumber;
string[] phrases = EngBasicPhrases.ToArray();
for (int i = 0; i < tableLayoutPanel1.Controls.Count; i++)
{
if (tableLayoutPanel1.Controls[i] is Button)
button1 = (Button)tableLayoutPanel1.Controls[i];
else
continue;
randomNumber = random.Next(0, EngBasicPhrases.Count - 1);
button1.Text = phrases[randomNumber];
EngBasicPhrases.RemoveAt(randomNumber);
}
phrases = FrBasicPhrases.ToArray();
for (int i = 0; i < tableLayoutPanel2.Controls.Count; i++)
{
if (tableLayoutPanel2.Controls[i] is Button)
button2 = (Button)tableLayoutPanel2.Controls[i];
else
continue;
randomNumber = random.Next(0, FrBasicPhrases.Count);
button2.Text = phrases[randomNumber];
FrBasicPhrases.RemoveAt(randomNumber);
}
}
private void Button_Click(object sender, EventArgs e)
{
if (firstClicked != null && secondClicked != null)
return;
Button clickedButton = sender as Button;
if (clickedButton == null)
return;
if (clickedButton.ForeColor == Color.Black)
return;
if (firstClicked == null)
{
firstClicked = clickedButton;
firstClicked.ForeColor = Color.Black;
return;
}
secondClicked = clickedButton;
secondClicked.ForeColor = Color.Black;
CheckForWinner1();
if (firstClicked.Text == secondClicked.Text)
{
firstClicked = null;
secondClicked = null;
}
else
timer1.Start();
}
private void CheckForWinner1()
{
Button button;
for (int i = 0; i < tableLayoutPanel1.Controls.Count; i++)
{
button = tableLayoutPanel1.Controls[i] as Button;
if (button != null && button.ForeColor == button.BackColor)
return;
}
MessageBox.Show("Congratulations!");
}
private void Button_Click2(object sender, EventArgs e)
{
if (firstClicked != null && secondClicked != null)
return;
Button clickedButton = sender as Button;
if (clickedButton == null)
return;
if (clickedButton.ForeColor == Color.Black)
return;
if (firstClicked == null)
{
firstClicked = clickedButton;
firstClicked.ForeColor = Color.Black;
return;
}
secondClicked = clickedButton;
secondClicked.ForeColor = Color.Black;
CheckForWinner2();
if (firstClicked.Text == secondClicked.Text)
{
firstClicked = null;
secondClicked = null;
}
else
timer1.Start();
}
private void CheckForWinner2()
{
Button button;
for (int i = 0; i < tableLayoutPanel2.Controls.Count; i++)
{
button = tableLayoutPanel2.Controls[i] as Button;
if (button != null && button.ForeColor == button.BackColor)
return;
}
MessageBox.Show("Congratulations!");
}
private void timer1_Tick(object sender, EventArgs e)
{
timer1.Stop();
firstClicked.ForeColor = firstClicked.BackColor;
secondClicked.ForeColor = secondClicked.BackColor;
firstClicked = null;
secondClicked = null;
}
I would suggest to use classes, so the task become trivial. Btw, since you are using winforms you can use "Tag" property to store a correct answer.
I built a small console app to highlight my idea:
using System;
using System.Collections.Generic;
namespace ConsoleApp9
{
public class GameObject
{
public int key { get; set; }
public string EN { get; set; }
public string FR { get; set; }
}
class Program
{
static void Main(string[] args)
{
List<string> EngBasicPhrases = new List<string>()
{
"Hello", "How are you?", "Hot", "Thank you", "Welcome",
"Let's go", "My name is...", "Cold", "Good luck",
"Congratulations", "Bless you","I forgot","Sorry","I'm fine",
"It's no problem","Don't worry","Here it is","What?","Of course",
"Boy","Girl","Man","Woman","Friend","Almost","Late"
};
List<string> FrBasicPhrases = new List<string>()
{
"Salut","Ca va?","Chaud", "Merci", "Bienvenu", "Allons-y","Je m'appelle","Du froid",
"Bonne chance","Felicitations","A vos souhaits","J'ai oublie","Desole","Je vais bien",
"Ce n'est pas grave","Ne t'en fais pas","Voila","Comment?","Bien sur","Un garcon","Une fille",
"Un home","Une femme","Un ami","Presque","En retard"
};
List<GameObject> list = new List<GameObject>();
int max = EngBasicPhrases.Count;
for (int i = 0; i < max; i++)
{
list.Add(new GameObject { key = i, EN = EngBasicPhrases[i], FR = FrBasicPhrases[i] });
}
Random rnd = new Random();
int nextIndex = rnd.Next(max);
Console.WriteLine($"Guess this: { list[nextIndex].EN}");
Console.WriteLine($"Youe answer is (type number, press enter):");
for (int i = 0; i < max; i++)
{
Console.WriteLine($"{list[i].key} - { list[i].FR}");
}
int answer = int.Parse(Console.ReadLine());
if(nextIndex == answer)
{
Console.WriteLine($"you won a game !");
}
else
{
Console.WriteLine($"you lost a game ... the correct answer was {list[nextIndex].key} - {list[nextIndex].FR} ");
}
Console.WriteLine($"");
Console.WriteLine($"Game over");
Console.ReadKey();
}
}
}
I hope it helps 馃槉

C# search checklistbox on textbox but don't remember checked or copy record twice to checklistbox C#

i have problems with searching checklistbox in textbox. When I have 1 parameter
ladujZBazy(string mustContains)
When I checked items on list in checkedListBox1 and search some items using textBox1 my previous check is gone.
I add 2nd parameter to your function(bool type)
void ladujZBazy(string mustContains, bool dropIndexes)
which will by default be false
private void dbopakowania_Load(object sender, EventArgs e)
{
ladujZBazy(null, false);
}
and And then call textbox's TextChanged event as false.
private void textBox1_TextChanged(object sender, EventArgs e)
{
ladujZBazy(textBox1.Text, false); //false
}
This time checked is not gone but copy record twice to checklistbox.. When value boolean is true I checked items on list in checkedListBox1 and search some items using textBox1 my previous check is gone. I want when i checked and search some items using textBox1 my previous checked is not gone and don't copy record twice to checklistbox.
Full Code:
namespace Email_Sender
{
public partial class dbopakowania : Form
{
EmailSender emailsender;
public List<List<string>> listOpakowaniaTabela = new List<List<string>>();
public string doZamowienia = "";
List<int> indexes = new List<int>();
string typZgloszenia;
public dbopakowania(EmailSender _emailsender, string _typZgloszenia)
{
InitializeComponent();
this.emailsender = _emailsender; //przechwycenie obiektu EmailSender do lokalnego obiektu tego samego typu
this.typZgloszenia = _typZgloszenia;
if (typZgloszenia == "ZWROT")
{
label1.Text = "Zwr贸膰 opakowania:";
btnGetItem.Text = "Zwr贸膰";
this.emailsender.txt_subject.Text = "Zwrot opakowa艅";
}
else if(typZgloszenia == "ZAMOWIENIE")
{
label1.Text = "Zam贸w opakowania:";
btnGetItem.Text = "Zam贸w";
this.emailsender.txt_subject.Text = "Zam贸wienie opakowa艅";
}
}
private void dbopakowania_Load(object sender, EventArgs e)
{
ladujZBazy(null, false);
}
private void button2_Click(object sender, EventArgs e)
{
if (label1.Text == "Zam贸w opakowania:")
{
for (int i = 0; i < checkedListBox1.Items.Count; i++)
{
if (checkedListBox1.GetItemCheckState(i) == CheckState.Checked)
{
AddValueToZam贸wienieOpakowan oknoZamowieniaOpakowania_Szczegoly = new AddValueToZam贸wienieOpakowan(this, indexes[i]);
oknoZamowieniaOpakowania_Szczegoly.ShowDialog();
if (doZamowienia != "")
{
this.emailsender.pozycja++;
this.emailsender.txt_msg.Text += emailsender.pozycja.ToString() + "." + " " + doZamowienia;
//this.emailsender.txt_subject.Clear();
//this.emailsender.txt_subject.Text = "Zam贸wienie opakowa艅";
}
}
}
this.Close();
}
else if (label1.Text == "Zwr贸膰 opakowania:")
{
for (int i = 0; i < checkedListBox1.Items.Count; i++)
{
if (checkedListBox1.GetItemCheckState(i) == CheckState.Checked)
{
ZwrotOpakowan oknoZamowieniaOpakowania_Szczegoly = new ZwrotOpakowan(this, indexes[i]);
oknoZamowieniaOpakowania_Szczegoly.ShowDialog();
if (doZamowienia != "")
{
this.emailsender.pozycja++;
this.emailsender.txt_msg.Text += emailsender.pozycja.ToString() + "." + " " + doZamowienia;
//this.emailsender.txt_subject.Clear();
//this.emailsender.txt_subject.Text = "Zam贸wienie opakowa艅";
}
}
}
this.Close();
}
else
{
MessageBox.Show("Nieoczekiwany B艂膮d - skontaktuj sie z admin", "B艂膮d", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
private void btn_close_Click(object sender, EventArgs e)
{
this.Close();
}
void ladujZBazy(string mustContains, bool dropIndexes)
{
if (dropIndexes)
{
checkedListBox1.Items.Clear();
listOpakowaniaTabela.Clear();
indexes.Clear();
}
bazaproduktowDBEntities dc = new bazaproduktowDBEntities();
var c1 = from d in dc.OpakowaniaTabela select d.NazwaOpakowania;
var c2 = from d in dc.OpakowaniaTabela select "(" + d.PartiaOpakowania + ")";
var c3 = from d in dc.OpakowaniaTabela select d.IloscOpakowania;
var c4 = from d in dc.OpakowaniaTabela select d.JednostkaOpakowania;
listOpakowaniaTabela.Add(c1.ToList());
listOpakowaniaTabela.Add(c2.ToList());
listOpakowaniaTabela.Add(c3.ToList());
listOpakowaniaTabela.Add(c4.ToList());
for (int i = 0; i < listOpakowaniaTabela[0].Count; i++)
{
string strToAdd = "";
for (int j = 0; j < listOpakowaniaTabela.Count; j++)
{
strToAdd += " " + listOpakowaniaTabela[j][i] + " ";
}
if (mustContains == null)
{
checkedListBox1.Items.Add(strToAdd);
indexes.Add(i);
}
else if (strToAdd.ToLower().Contains(mustContains.ToLower()))
{
checkedListBox1.Items.Add(strToAdd);
indexes.Add(i);
}
}
}
private void textBox1_TextChanged(object sender, EventArgs e)
{
ladujZBazy(textBox1.Text, false); //false
}
}
Any Solution? C#

WPF User Interface not updating without moving mouse

I am using background work to load some content but something really odd is happening the UI is not updating and it just begin to happen suddenly,
here follows the code
here is the button click
public void CarregaPaginaCTeTomador(object sender, RoutedEventArgs e)
{
if (ClassControleInstancia.CTeTomador == null)
{
ClassControleInstancia.CTeTomador = new Page_CTE_Tomador();
}
BackgroundWorker LoadPageWorker = new BackgroundWorker();
LoadPageWorker.DoWork += LoadPageWorker_DoWorkCteTomador;
LoadPageWorker.RunWorkerCompleted += LoadPageWorker_RunWorkerCompleted;
LoadPageWorker.RunWorkerAsync();
}
here is the 1掳 background work
private void LoadPageWorker_DoWorkCteTomador(object sender, DoWorkEventArgs e)
{
Console.WriteLine("Antes do DoEvents");
System.Windows.Forms.Application.DoEvents();
Console.WriteLine("Apos o DoEvents");
ClassControleInstancia.JanelaPrincipal.Dispatcher.Invoke(() =>
{
_mainFrame.Navigate(ClassControleInstancia.CTeTomador);
ClassControleInstancia.CTeTomador.RefreshContent();
});
}
private void LoadPageWorker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
WaitNSeconds(80);
FrameCurrentPage();
}
Inside this ClassControleInstancia.CTeTomador.RefreshContent(); has another background work should this be the reason why the ui is getting stocked ?
Cause I am not seeing any problem with the code I am going mad cause I tried alread remove the bgwork but it still gets stocked.
the other bgwork is
private void CarregaGrid(int pagina, int quantidade, int TipoArquivo, int AscDesc, bool inognoreNot = false) //0 crescente 1 desc
{
//show the loader
ClassControleInstancia.JanelaPrincipal.Loader.Visibility = Visibility.Visible;
ClassControleInstancia.JanelaPrincipal.Loader_Abort.Visibility = Visibility.Hidden;
ClassControleInstancia.JanelaPrincipal.Loader_text.Visibility = Visibility.Hidden;
ClassControleInstancia.JanelaPrincipal.Loader_porgress.Visibility = Visibility.Hidden;
BackgroundWorker GridLoader = new BackgroundWorker();
GridLoader.DoWork += GridLoader_DoWork;
GridLoader.RunWorkerCompleted += GridLoader_RunWorkerCompleted;
GridLoader.RunWorkerAsync();
}
private void GridLoader_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
dgUsers.Items.Refresh();
ClassControleInstancia.JanelaPrincipal.Loader.Visibility = Visibility.Hidden;
ButtonsSelector config = new ButtonsSelector();
config.OnViewStart(TipoArquivoOrdenacaoEnum.CTE_NaoTomador, botoesSelector(), "cte-nao-tomador");
}
private void GridLoader_DoWork(object sender, DoWorkEventArgs e)
{
Dispatcher.Invoke((() =>
{
ClassControleInstancia.JanelaPrincipal.Loader_percentage.Width = new GridLength(0);
}));
CurrentPage = GridParams.Pagina;
CurrentMaxRows = GridParams.QuantidadePorPagina;
ObjSenhaWebApi Senha = new ObjSenhaWebApi(Conexao.ARQBancoDeDados().BuscaSenhaWebApiUsuario());
ObjPesquisaNotas PesquisaNotas = new ObjPesquisaNotas();
PesquisaNotas.IdEmpresa = ClassControleInstancia.EmpresaSelecionada.EMP_SEQUENCIA_ORI;
PesquisaNotas.Pagina = GridParams.Pagina;
PesquisaNotas.QntdMostrar = GridParams.QuantidadePorPagina;
PesquisaNotas.Ordenacao = GridParams.TipoArquivo;
PesquisaNotas.CrescenteDecrescente = GridParams.IsAscDesc;
PesquisaNotas._ObjListaParametrosNfeSaida = new ObjListaParametrosNfeSaida();
PesquisaNotas._ObjListaParametrosNfeSaida.UsuarioId = Conexao.ARQBancoDeDados().BuscaSequenciaClienteOri();
PesquisaNotas.tipoTomador = 1;
#region CamposDaPesquisa
P_ADICIONA_CAMPOS_PESQUISA(PesquisaNotas);
#endregion
int V_EMPRESA = 0;
string V_NUMERO_NOTA = "";
Dispatcher.Invoke((Action)(() => V_NUMERO_NOTA = EDT_NUMERO_NOTA.Text.Trim()));
if (ClassControleInstancia.EmpresaSelecionada != null)
{
V_EMPRESA = ClassControleInstancia.EmpresaSelecionada.EMP_SEQUENCIA;
string V_FORNECEDOR = "";
Dispatcher.Invoke((Action)(() => V_FORNECEDOR = CbFornecedor.Text.ToString()));
Dispatcher.Invoke((Action)(() => dgUsers.ItemsSource = null));
List<Cte> ListaNotas = ArquivarNfeRest.ArquivarNfeRest.BuscaNotaSaida<Cte>(Senha, PesquisaNotas);
if (ListaNotas != null)
{
if (ListaNotas.Count() > 0)
{
Dispatcher.Invoke((Action)(() => nuvenzita_no_itens.Visibility = Visibility.Hidden));
}
else
{
Dispatcher.Invoke((Action)(() => nuvenzita_no_itens.Visibility = Visibility.Visible));
}
}
else
{
Dispatcher.Invoke((Action)(() => nuvenzita_no_itens.Visibility = Visibility.Visible));
}
//Colocar em negrito todos os matchs com a outra lista
List<string> ListaNegrito = ClassControleListaNegrito.BuscaLista(ClassControleInstancia.EmpresaSelecionada.EMP_SEQUENCIA, TipoArquivoOrdenacaoEnum.CTE_NaoTomador, true).ValorLista;
foreach (var item in ListaNotas)
{
foreach (var item2 in ListaNegrito)
{
if (item2 == item.CteSequencia.ToString())
{
item.NEGRITO = true;
}
}
}
ObjRetornoCount _ObjRetornoCount = ArquivarNfeRest.ArquivarNfeRest.BuscaQntdNotaSaida<Cte>(Senha, PesquisaNotas);
int QntdPaginas = _ObjRetornoCount.QntdPaginas;
int QntdNotas = _ObjRetornoCount.QntdTotal;
//Retira aviso vermelho (confima letura)
if (GridParams.IgnorarAlerta != true)
{
ClassDoReadNotification<Cte>.Verify();
ClassControleInstancia.Notifications.IsCteNaoTomadorRead = 1;
ClassControleInstancia.JanelaPrincipal.AlertaNovasNotas();
}
Dispatcher.Invoke((Action)(() =>
{
totalItensFiltrados = QntdNotas;
itensNoFiltro = ListaNotas;
if (VerificaSeTemFiltro() == 0)
{
paginatorTotal.Content = "N潞 Total Doctos: " + (QntdNotas);
}
else
{
paginatorTotal.Content = "N潞 Total Doctos Filtrados: " + (QntdNotas);
}
Pagenizer.getButtons(footer, QntdPaginas, CurrentPage, CurrentMaxRows, "cte-nao-tomador");
}));
//List<ObjSincronizados> ListaNotas = Conexao.ARQBancoDeDados().BuscaListaSincronizados(V_EMPRESA, V_NUMERO_NOTA, V_DATA_INICIAL, V_DATA_FINAL, V_FORNECEDOR);
Dispatcher.Invoke((Action)(() => dgUsers.ItemsSource = ListaNotas));
Dispatcher.Invoke((Action)(() =>
{
int tt = dgUsers.Items.OfType<Cte>().Where(x => x.MARCADO == true).Count();
int ttAll = dgUsers.Items.OfType<Cte>().Where(x => x.MARCADO == true || x.MARCADO == false).Count();
btCounter.Content = "Selecionados " + tt.ToString() + " de " + ttAll.ToString();
headerCheckBox.IsChecked = false;
}
));
}
}

How to make a xaml textbox in silverlight accept only numbers with maximum one decimal point precision

How to make a xaml textbox in silverlight accept only numbers with maximum one decimal point precison. I have tried the answers in this question How to make a textBox accept only Numbers and just one decimal point in Windows 8. But it did not work. How can I do this ?
You can write a function like this,
txtDiscount.KeyDown += new KeyEventHandler(EnsureNumbers);
//Method to allow only numbers,
void EnsureNumbers(object sender, KeyEventArgs e)
{
if (e.Key == Key.Tab)
{
return;
}
bool result = EnsureDecimalPlaces();
if (result == false)
{
var thisKeyStr = "";
if (e.PlatformKeyCode == 190 || e.PlatformKeyCode == 110)
{
thisKeyStr = ".";
}
else
{
thisKeyStr = e.Key.ToString().Replace("D", "").Replace("NumPad", "");
}
var s = (sender as TextBox).Text + thisKeyStr;
var rStr = "^[0-9]+[.]?[0-9]*$";
var r = new Regex(rStr, RegexOptions.IgnoreCase);
e.Handled = !r.IsMatch(s);
}
else
{
e.Handled = true;
}
}
Method to ensure only 1 decimal,
bool EnsureDecimalPlaces()
{
string inText = txtDiscount.Text;
int decPointIndex = inText.IndexOf('.');
if (decPointIndex < 1 || decPointIndex == 1)
{
return false;
}
else
return true;
}

How to make simple basic data validations

I have a small web form that user will enter some patient data and it will get passed along to insurance hub. I just want to provide some basic validation e.g the social security number sb numerics, a legnth of 10, age sb numercial and maybe over a certain age number, etc. how can i do this, here in this code ?
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
...
namespace PBM
{
public partial class MainPage : UserControl
{
private DomainServicePBM _context = new DomainServicePBM();
public MainPage()
{
InitializeComponent();
this.ObjPatient = new Patient();
}
private void btnSearch_Click(object sender, RoutedEventArgs e)
{
dgPatient.ItemsSource = _context.Patients;
_context.Load(_context.GetPatientsBySearchQuery(sTxtFirstName.Text.Trim(), sTxtLastName.Text.Trim(), sCombGender.SelectedIndex == 1 ? false: sCombGender.SelectedIndex == 2 ? true : new bool?()));
PagedCollectionView itemListView = new PagedCollectionView(dgPatient.ItemsSource);
dpPatient.Source = itemListView;
}
private void btnSave_Click(object sender, RoutedEventArgs e)
{
//_context = new DomainServicePBM();
if (ObjPatient != null && ObjPatient.PatientID > 0)
{
Patient p = _context.Patients.Single(pat => pat.PatientID == this.ObjPatient.PatientID);
p.FirstName = txtFirstName.Text.Trim();
p.LastName = txtLastName.Text.Trim();
p.MiddleName = txtMiddleName.Text.Trim();
p.Gender = cmbGender.SelectedIndex == 0 ? false : true;
p.DOB = ctrlDTDOB.SelectedDate;
p.Age = Convert.ToInt32(txtAge.Text.Trim());
p.MaterialStatus = cmbMaritalStatus.SelectedIndex == 0 ? (byte)MaritalStatus.Single :
cmbMaritalStatus.SelectedIndex == 1 ? (byte)MaritalStatus.Married : (byte)MaritalStatus.Divorced;
p.SSN = txtSSN.Text.Trim();
p.MedicalID = txtMedicalID.Text.Trim();
p.Medicare = txtMedicare.Text.Trim();
p.Race = txtRace.Text.Trim();
p.AdmitFrom = ctrlDTAdmitFrom.SelectedDate;
}
else
{
_context.Patients.Add(new Patient
{
FirstName = txtFirstName.Text.Trim(),
LastName = txtLastName.Text.Trim(),
MiddleName = txtMiddleName.Text.Trim(),
Gender = cmbGender.SelectedIndex == 0 ? false : true,
DOB = ctrlDTDOB.SelectedDate,
Age = Convert.ToInt32(txtAge.Text.Trim()),
MaterialStatus = cmbMaritalStatus.SelectedIndex == 0 ? (byte)MaritalStatus.Single :
cmbMaritalStatus.SelectedIndex == 1 ? (byte)MaritalStatus.Married : (byte)MaritalStatus.Divorced,
SSN = txtSSN.Text.Trim(),
MedicalID = txtMedicalID.Text.Trim(),
Medicare = txtMedicare.Text.Trim(),
Race = txtRace.Text.Trim(),
AdmitFrom = ctrlDTAdmitFrom.SelectedDate
});
}
_context.SubmitChanges(
(SubmitOperation so) =>
{
if (so.HasError)
{
MessageBox.Show("Patient Info Not Saved.");
}
else
{
MessageBox.Show("Patient Info Saved Successfully.");
ResetControls();
this.ObjPatient = new Patient();
}
}, null);
}
Patient ObjPatient { get; set; }
private void btnAdd_Click(object sender, RoutedEventArgs e)
{
this.ObjPatient = new Patient();
}
private void ResetControls()
{
txtFirstName.Text = txtLastName.Text = txtMiddleName.Text = txtMedicalID.Text = txtMedicare.Text = txtRace.Text = txtSSN.Text = txtAge.Text = string.Empty;
cmbGender.SelectedIndex = cmbMaritalStatus.SelectedIndex = 0;
ctrlDTAdmitFrom.SelectedDate = ctrlDTDOB.SelectedDate = DateTime.Now;
}
private void btnDelete_Click(object sender, RoutedEventArgs e)
{
this.ObjPatient = dgPatient.SelectedItem as Patient;
if (this.ObjPatient != null)
{
_context.Patients.Remove(this.ObjPatient);
_context.SubmitChanges(
(SubmitOperation so) =>
{
if (so.HasError)
{
MessageBox.Show(so.Error.ToString());
}
else
{
MessageBox.Show("Patient Deleted Successfully.");
}
}, null);
}
else
{
MessageBox.Show("Please select patient first.");
}
}
private void btnEdit_Click(object sender, RoutedEventArgs e)
{
this.ObjPatient = dgPatient.SelectedItem as Patient;
if (ObjPatient != null)
{
txtFirstName.Text = ObjPatient.FirstName;
txtLastName.Text = ObjPatient.LastName;
txtMiddleName.Text = ObjPatient.MiddleName;
cmbGender.SelectedIndex = ObjPatient.Gender == true ? 0 : 1;
cmbMaritalStatus.SelectedIndex = ObjPatient.MaterialStatus == 1 ? 0 : ObjPatient.MaterialStatus == 2 ? 1 : 2;
txtAge.Text = Convert.ToString(ObjPatient.Age);
ctrlDTDOB.SelectedDate = ObjPatient.DOB;
ctrlDTAdmitFrom.SelectedDate = Convert.ToDateTime(ObjPatient.AdmitFrom);
txtMedicalID.Text = ObjPatient.MedicalID;
txtMedicare.Text = ObjPatient.Medicare;
txtRace.Text = ObjPatient.Race;
txtSSN.Text = ObjPatient.SSN;
}
}
private void dpPatient_PageIndexChanged(object sender, EventArgs e)
{
_context.Patients.Skip(dpPatient.PageIndex).Take(1);
}
}
public enum MaritalStatus {
Single=0,
Married=1,
Divorced = 2
}
}
I would take a look at the DataAnnations namespace. It provides attributes for defining all sorts of validations. You'll need to apply these attributes to the properties that need validation. Then you'll need a way to check if these attributes pass validation. This is typically done using reflection. Take a look at this answer.

Categories