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.
Related
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);
}
Im having a problem when i try to filter my gridview trough combobox basicly when i click on the button "Procurar" the grid doesnt update but the row im in just switch. i will explain with the images
then when i choose a different Category "Categoria" it does this
Basicically it overwrote my original row with the new one that as the Categoria "Vegan".
here is the code:
private void btnSearch_Click(object sender, EventArgs e) {
string receitas = #"receitas.txt";
if (File.Exists(receitas)) {
StreamReader sr2 = File.OpenText(receitas);
string linha2 = "";
int x = 0;
while ((linha2 = sr2.ReadLine()) != null) {
string[] campos2 = linha2.Split(';');
if (comboBoxCategorias.SelectedItem.ToString() == campos2[2]) {
if ((txtTitulo.Text == "") || (txtIngredientes.Text == "")) {
dataGridReceitas[0, x].Value = campos2[0];
dataGridReceitas[1, x].Value = campos2[1];
dataGridReceitas[2, x].Value = campos2[2];
dataGridReceitas[3, x].Value = campos2[3];
x++;
}
}
}
sr2.Close();
}
}
private void btnSearch_Click(object sender, EventArgs e)
{
dataGridReceitas.Rows.Clear();
string receitas = #"receitas.txt";
if (File.Exists(receitas))
{
StreamReader sr2 = File.OpenText(receitas);
string linha2 = "";
int x = 0;
while ((linha2 = sr2.ReadLine()) != null)
{
string[] campos2 = linha2.Split(';');
if(comboBoxCategorias.SelectedItem.ToString() == campos2[2])
{
if((txtTitulo.Text == "") || (txtIngredientes.Text == ""))
{
dataGridReceitas.Rows.Add(1);
dataGridReceitas[0, x].Value = campos2[0];
dataGridReceitas[1, x].Value = campos2[1];
dataGridReceitas[2, x].Value = campos2[2];
dataGridReceitas[3, x].Value = campos2[3];
x++;
}
}
}
sr2.Close();
}
}
the solution was adding the code dataGridReceitas.Rows.Clear(); to clear the grid and just appearing the rows i wanted also adding the DataGridReceitas.Rows.Add(1) so when the search result is bigger than 1 the aplication dont crash
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#
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;
}
));
}
}
I have a product ordering page with various product option dropdownlists which are inside a repeater. The "Add To Cart" button is "inactive" until all the options have a selection. Technically, the "Add To Cart" button has two images: a grey one which is used when the user has not selected choices for all options available to a product and an orange one which is used when the user has made a selection from each dropdownlist field.These images are set by the ShowAddToBasket and HideAddToBasket functions.
The dropdownlist fields are connected in that a selection from the first field will determine a selection for the second and sometimes third field. If the second field is NOT pre-set by the first field, then the second field will determine the value for the third field. The first dropdownlist field is never disabled, but the other two can be based on what options have been selected.
There are a few products that have all 3 of their dropdownlists pre-set to certain choices upon entering their page. This means they are all disabled and cannot be changed by the user. Regardless of whether the user enters in a quantity or not, the "Add To Cart" button NEVER activates. I cannot for the life of me figure out how to change it so that, in these rare circumstances, the "Add to Cart" button is automatically set to active once a quantity has been entered. The dropdownlists still have options selected in these pages--it's just that they are fixed and cannot be changed by the user.
Is there anyway I can get the selected value or selected index of these dropdownlist fields upon entering a product page? I want to be able to check to see if they are truly "empty" or if they do have selections made so I can set the "Add to Cart" button accordingly.
Any help would be great because I'm really stuck on this one! :(
Here is the code behind (I removed a lot of the unimportant functions):
protected void Page_Init(object sender, System.EventArgs e)
{
string MyPath = HttpContext.Current.Request.Url.AbsolutePath;
MyPath = MyPath.ToLower();
_Basket = AbleContext.Current.User.Basket;
RedirQryStr = "";
_ProductId = AlwaysConvert.ToInt(Request.QueryString["ProductId"]);
if (Request.QueryString["LineID"] != null)
{
int LineID = Convert.ToInt32(Request.QueryString["LineID"].ToString());
int itemIndex = _Basket.Items.IndexOf(LineID);
BasketItem item = _Basket.Items[itemIndex];
OldWeight.Text = item.Weight.ToString();
OldQty.Text = item.Quantity.ToString();
OldPrice.Text = item.Price.ToString();
}
int UnitMeasure = 0;
SetBaidCustoms(ref UnitMeasure);
GetPrefinishNote();
_ProductId = AlwaysConvert.ToInt(Request.QueryString["ProductId"]);
_Product = ProductDataSource.Load(_ProductId);
if (_Product != null)
{
//GetPercentage();
int _PieceCount = 0;
double _SurchargePercent = 0;
CheckoutHelper.GetItemSurcargePercent(_Product, ref _PieceCount, ref _SurchargePercent);
SurchargePieceCount.Text = _PieceCount.ToString();
SurchargePercent.Text = _SurchargePercent.ToString();
//add weight
BaseWeight.Value = _Product.Weight.ToString();
//DISABLE PURCHASE CONTROLS BY DEFAULT
AddToBasketButton.Visible = false;
rowQuantity.Visible = false;
//HANDLE SKU ROW
trSku.Visible = (ShowSku && (_Product.Sku != string.Empty));
if (trSku.Visible)
{
Sku.Text = _Product.Sku;
}
//HANDLE PART/MODEL NUMBER ROW
trPartNumber.Visible = (ShowPartNumber && (_Product.ModelNumber != string.Empty));
if (trPartNumber.Visible)
{
PartNumber.Text = _Product.ModelNumber;
}
//HANDLE REGPRICE ROW
if (ShowMSRP)
{
decimal msrpWithVAT = TaxHelper.GetShopPrice(_Product.MSRP, _Product.TaxCode != null ? _Product.TaxCode.Id : 0);
if (msrpWithVAT > 0)
{
trRegPrice.Visible = true;
RegPrice.Text = msrpWithVAT.LSCurrencyFormat("ulc");
}
else trRegPrice.Visible = false;
}
else trRegPrice.Visible = false;
// HANDLE PRICES VISIBILITY
if (ShowPrice)
{
if (!_Product.UseVariablePrice)
{
trBasePrice.Visible = true;
BasePrice.Text = _Product.Price.ToString("F2") + BairdLookUp.UnitOfMeasure(UnitMeasure);
trOurPrice.Visible = true;
trVariablePrice.Visible = false;
}
else
{
trOurPrice.Visible = false;
trVariablePrice.Visible = true;
VariablePrice.Text = _Product.Price.ToString("F2");
string varPriceText = string.Empty;
Currency userCurrency = AbleContext.Current.User.UserCurrency;
decimal userLocalMinimum = userCurrency.ConvertFromBase(_Product.MinimumPrice.HasValue ? _Product.MinimumPrice.Value : 0);
decimal userLocalMaximum = userCurrency.ConvertFromBase(_Product.MaximumPrice.HasValue ? _Product.MaximumPrice.Value : 0);
if (userLocalMinimum > 0)
{
if (userLocalMaximum > 0)
{
varPriceText = string.Format("(between {0} and {1})", userLocalMinimum.LSCurrencyFormat("ulcf"), userLocalMaximum.LSCurrencyFormat("ulcf"));
}
else
{
varPriceText = string.Format("(at least {0})", userLocalMinimum.LSCurrencyFormat("ulcf"));
}
}
else if (userLocalMaximum > 0)
{
varPriceText = string.Format("({0} maximum)", userLocalMaximum.LSCurrencyFormat("ulcf"));
}
phVariablePrice.Controls.Add(new LiteralControl(varPriceText));
}
}
//UPDATE QUANTITY LIMITS
if ((_Product.MinQuantity > 0) && (_Product.MaxQuantity > 0))
{
string format = " (min {0}, max {1})";
QuantityLimitsPanel.Controls.Add(new LiteralControl(string.Format(format, _Product.MinQuantity, _Product.MaxQuantity)));
QuantityX.MinValue = _Product.MinQuantity;
QuantityX.MaxValue = _Product.MaxQuantity;
}
else if (_Product.MinQuantity > 0)
{
string format = " (min {0})";
QuantityLimitsPanel.Controls.Add(new LiteralControl(string.Format(format, _Product.MinQuantity)));
QuantityX.MinValue = _Product.MinQuantity;
}
else if (_Product.MaxQuantity > 0)
{
string format = " (max {0})";
QuantityLimitsPanel.Controls.Add(new LiteralControl(string.Format(format, _Product.MaxQuantity)));
QuantityX.MaxValue = _Product.MaxQuantity;
}
if (QuantityX.MinValue > 0) QuantityX.Text = QuantityX.MinValue.ToString();
AddToWishlistButton.Visible = AbleContext.Current.StoreMode == StoreMode.Standard;
}
else
{
this.Controls.Clear();
}
if (!Page.IsPostBack)
{
if (Request.QueryString["Action"] != null)
{
if (Request.QueryString["Action"].ToString().ToLower() == "edit")
{
SetEdit();
}
}
}
}
protected void Page_Load(object sender, System.EventArgs e)
{
if (_Product != null)
{
if (ViewState["OptionDropDownIds"] != null)
{
_OptionDropDownIds = (Hashtable)ViewState["OptionDropDownIds"];
}
else
{
_OptionDropDownIds = new Hashtable();
}
if (ViewState["OptionPickerIds"] != null)
{
_OptionPickerIds = (Hashtable)ViewState["OptionPickerIds"];
}
else
{
_OptionPickerIds = new Hashtable();
}
_SelectedOptionChoices = GetSelectedOptionChoices();
OptionsList.DataSource = GetProductOptions();
OptionsList.DataBind();
//set all to the first value
foreach (RepeaterItem rptItem in OptionsList.Items)
{
DropDownList OptionChoices = (DropDownList)rptItem.FindControl("OptionChoices");
OptionChoices.SelectedIndex = 1;
}
TemplatesList.DataSource = GetProductTemplateFields();
TemplatesList.DataBind();
KitsList.DataSource = GetProductKitComponents();
KitsList.DataBind();
}
if (!Page.IsPostBack)
{
if (_Product.MSRP != 0)
{
salePrice.Visible = true;
RetailPrice.Text = _Product.MSRP.ToString("$0.00");
}
DataSet ds = new DataSet();
DataTable ResultTable = ds.Tables.Add("CatTable");
ResultTable.Columns.Add("OptionID", Type.GetType("System.String"));
ResultTable.Columns.Add("OptionName", Type.GetType("System.String"));
ResultTable.Columns.Add("LinkHeader", Type.GetType("System.String"));
foreach (ProductOption PhOpt in _Product.ProductOptions)
{
string MasterList = GetProductMaster(_ProductId, PhOpt.OptionId);
string PerFootVal = "";
string LinkHeader = "";
string DefaultOption = "no";
string PrefinishMin = "0";
bool VisPlaceholder = true;
ProductDisplayHelper.TestForVariantDependency(ref SlaveHide, _ProductId, PhOpt, ref PrefinishMin, ref PerFootVal, ref LinkHeader, ref VisPlaceholder, ref HasDefault, ref DefaultOption);
if (PrefinishMin == "")
PrefinishMin = "0";
DataRow dr = ResultTable.NewRow();
dr["OptionID"] = PhOpt.OptionId + ":" + MasterList + ":" + PerFootVal + ":" + DefaultOption + ":" + PrefinishMin;
Option _Option = OptionDataSource.Load(PhOpt.OptionId);
dr["OptionName"] = _Option.Name;
dr["LinkHeader"] = LinkHeader;
ResultTable.Rows.Add(dr);
}
//Bind the data to the Repeater
ItemOptions.DataSource = ds;
ItemOptions.DataMember = "CatTable";
ItemOptions.DataBind();
//determine if buttons show
if (ItemOptions.Items.Count == 0)
{
ShowAddToBasket(1);
resetBtn.Visible = true;
}
else
{
HideAddToBasket(3);
}
if (Request.QueryString["Action"] != null)
{
ShowAddToBasket(1);
SetDllAssociation(false);
}
ShowHideDrops();
}
}
private void HideAddToBasket(int Location)
{
AddToBasketButton.Visible = false;
AddToWishlistButton.Visible = false;
resetBtn.Visible = false;
if (Request.QueryString["Action"] == null)
{
SelectAll.Visible = true;
WishGray.Visible = true;
if (Request.QueryString["OrderItemID"] == null)
BasketGray.Visible = true;
else
UpdateButton.Visible = false;
}
else
{
UpdateButton.Visible = true;
NewButtons.Visible = false;
}
if ((_Product.MinQuantity == 1) & (_Product.MaxQuantity == 1))
{
AddToWishlistButton.Visible = false;
BasketGray.Visible = false;
}
}
private void ShowAddToBasket(int place)
{
resetBtn.Visible = true;
if (Request.QueryString["Action"] != null)
{
UpdateButton.Visible = true;
NewButtons.Visible = false;
}
else
{
UpdateButton.Visible = false;
SelectAll.Visible = false;
WishGray.Visible = false;
BasketGray.Visible = false;
if (Request.QueryString["OrderItemID"] == null)
{
AddToBasketButton.Visible = true;
resetBtn.Visible = true;
AddToWishlistButton.Visible = true;
}
else
{
UpdateButton.Visible = true;
AddToBasketButton.Visible = false;
}
}
if ((_Product.MinQuantity == 1) & (_Product.MaxQuantity == 1))
{
AddToWishlistButton.Visible = false;
BasketGray.Visible = false;
resetBtn.Visible = true;
}
}
protected void OptionChoices_DataBound(object sender, EventArgs e)
{
DropDownList ddl = (DropDownList)sender;
if (ddl != null)
{
//bb5.Text = "ddl !=null<br />"; works
List<OptionChoiceItem> ds = (List<OptionChoiceItem>)ddl.DataSource;
if (ds != null && ds.Count > 0)
{
int optionId = ds[0].OptionId;
Option opt = OptionDataSource.Load(optionId);
ShowAddToBasket(4);
OptionChoiceItem oci = ds.FirstOrDefault<OptionChoiceItem>(c => c.Selected);
if (oci != null)
{
ListItem item = ddl.Items.FindByValue(oci.ChoiceId.ToString());
if (item != null)
{
ddl.ClearSelection();
item.Selected = true;
}
}
if (opt != null && !opt.ShowThumbnails)
{
if (!_OptionDropDownIds.Contains(optionId))
{
// bb5.Text = "!_OptionDropDownIds.Contains(optionId)<br />"; works
_OptionDropDownIds.Add(optionId, ddl.UniqueID);
}
if (_SelectedOptionChoices.ContainsKey(optionId))
{
ListItem selectedItem = ddl.Items.FindByValue(_SelectedOptionChoices[optionId].ToString());
if (selectedItem != null)
{
ddl.ClearSelection();
selectedItem.Selected = true;
//bb5.Text = "true: " + selectedItem.Selected.ToString()+"<br />"; doesn't work
}
}
StringBuilder imageScript = new StringBuilder();
imageScript.Append("<script type=\"text/javascript\">\n");
imageScript.Append(" var " + ddl.ClientID + "_Images = {};\n");
foreach (OptionChoice choice in opt.Choices)
{
if (!string.IsNullOrEmpty(choice.ImageUrl))
{
imageScript.Append(" " + ddl.ClientID + "_Images[" + choice.Id.ToString() + "] = '" + this.Page.ResolveUrl(choice.ImageUrl) + "';\n");
}
}
imageScript.Append("</script>\n");
ScriptManager scriptManager = ScriptManager.GetCurrent(this.Page);
if (scriptManager != null)
{
ScriptManager.RegisterClientScriptBlock(this, this.GetType(), ddl.ClientID, imageScript.ToString(), false);
}
else
{
Page.ClientScript.RegisterClientScriptBlock(this.GetType(), ddl.ClientID, imageScript.ToString());
}
}
}
ddl.Attributes.Add("onChange", "OptionSelectionChanged('" + ddl.ClientID + "');");
}
}
protected Dictionary<int, int> GetSelectedOptionChoices()
{
HttpRequest request = HttpContext.Current.Request;
Dictionary<int, int> selectedChoices = new Dictionary<int, int>();
if (Page.IsPostBack)
{
foreach (int key in _OptionDropDownIds.Keys)
{
string value = (string)_OptionDropDownIds[key];
Trace.Write(string.Format("Checking For - OptionId:{0} DropDownId:{1}", key, value));
string selectedChoice = request.Form[value];
if (!string.IsNullOrEmpty(selectedChoice))
{
int choiceId = AlwaysConvert.ToInt(selectedChoice);
if (choiceId != 0)
{
Trace.Write(string.Format("Found Selected Choice : {0} - {1}", key, choiceId));
selectedChoices.Add(key, choiceId);
}
}
}
foreach (int key in _OptionPickerIds.Keys)
{
string value = (string)_OptionPickerIds[key];
Trace.Write(string.Format("Checking For - OptionId:{0} PickerId:{1}", key, value));
string selectedChoice = request.Form[value];
if (!string.IsNullOrEmpty(selectedChoice))
{
int choiceId = AlwaysConvert.ToInt(selectedChoice);
if (choiceId != 0)
{
Trace.Write(string.Format("Found Selected Choice : {0} - {1}", key, choiceId));
selectedChoices.Add(key, choiceId);
}
}
}
}
else
{
string optionList = Request.QueryString["Options"];
ShowAddToBasket(2);
if (!string.IsNullOrEmpty(optionList))
{
string[] optionChoices = optionList.Split(',');
if (optionChoices != null)
{
foreach (string optionChoice in optionChoices)
{
OptionChoice choice = OptionChoiceDataSource.Load(AlwaysConvert.ToInt(optionChoice));
if (choice != null)
{
_SelectedOptionChoices.Add(choice.OptionId, choice.Id);
}
}
return _SelectedOptionChoices;
}
}
}
return selectedChoices;
}
protected void SetDDLs(object sender, EventArgs e)
{
bool isRandom = false;
if (LengthDDL.Text != "")
isRandom = true;
SetDllAssociation(isRandom);
}
Try accessing the values in the Page_Load event. I don't believe the values are bound yet in Page_Init