WPF User Interface not updating without moving mouse - 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;
}
));
}
}

Related

Why i'm getting cross thread exception while updating label in backgroundworker progresschanged event?

I have a backgroundworker dowork where inside I start a new backgroundworker
DirectoryInfo MySubDirectory;
List<FileInfo> l;
object[] CurrentStatus;
private void _FileProcessingWorker_DoWork(object sender, DoWorkEventArgs e)
{
int countmore = 0;
try
{
DirectoryInfo[] MySubDirectories = (DirectoryInfo[])e.Argument;
for (int i = 0; i < MySubDirectories.GetLength(0); i++)
{
MySubDirectory = MySubDirectories[i];
l = new List<FileInfo>();
if (_FileCountingWorker.IsBusy == false)
_FileCountingWorker.RunWorkerAsync();
CurrentStatus = new object[6];
int totalFiles = l.Count;
CurrentStatus[3] = i.ToString();
countmore += totalFiles;
CurrentStatus[4] = countmore;
_FileProcessingWorker.ReportProgress(0, CurrentStatus);
string CurrentDirectory = "Current Directory: " + MySubDirectory.Name;
foreach (FileInfo MyFile in l)
{
CurrentStatus = new object[6];
if (_FileProcessingWorker.CancellationPending)
{
e.Cancel = true;
return;
}
if (MyFile.Extension.ToLower() == ".cs" || MyFile.Extension.ToLower() == ".vb")
{
string CurrentFile = "Current File: " + MyFile.Name;
string CurrentFileWithPath = MyFile.FullName;
CurrentStatus[0] = CurrentDirectory;
CurrentStatus[1] = CurrentFile;
_FileProcessingWorker.ReportProgress(0, CurrentStatus);
List<string> Result = SearchInFile(CurrentFileWithPath, "if");
if (Result != null && Result.Count > 0)
{
CurrentStatus[2] = Result;
_FileProcessingWorker.ReportProgress(0, CurrentStatus);
}
}
}
}
}
catch (Exception err)
{
return;
}
}
I'm checking the other backgroundworker is not busy if not start it
if (_FileCountingWorker.IsBusy == false)
_FileCountingWorker.RunWorkerAsync();
In the new backgroundworker dowork event
private void _FileCountingWorker_DoWork(object sender, DoWorkEventArgs e)
{
CountFiles(MySubDirectory, l);
}
In CountFiles
int countingFiles = 0;
private void CountFiles(DirectoryInfo di, List<FileInfo> l)
{
try
{
l.AddRange(di.EnumerateFiles());
}
catch
{
string fff = "";
}
try
{
if (di.FullName != BasePath)
{
IEnumerable<DirectoryInfo> subDirs = di.EnumerateDirectories();
if (subDirs.Count() > 0)
{
foreach (DirectoryInfo dir in subDirs)
{
CountFiles(dir, l);
countingFiles += 1;
if (countingFiles == 8382)
{
string hhhhh = "";
}
CurrentStatus[5] = countingFiles;
_FileCountingWorker.ReportProgress(0,CurrentStatus);
}
}
}
}
catch
{
string yyy = "";
}
}
Then in the second backgroundworker progresschanged
private void _FileCountingWorker_ProgressChanged(object sender, ProgressChangedEventArgs e)
{
if (typeof(object[]) == e.UserState.GetType())
{
object[] StatusMsg = (object[])e.UserState;
if (6 == StatusMsg.GetLength(0))
{
if (StatusMsg[5] != null)
{
lblCountingFiles.Text = StatusMsg[5].ToString();
}
}
}
}
The exception is on the line:
lblCountingFiles.Text = StatusMsg[5].ToString();
Cross-thread operation not valid: Control 'lblCountingFiles' accessed from a thread other than the thread it was created on
I'm updating the label in the ProgressChanged event. Why am I getting the exception?
And how should I solve it?
You are calling _FileCountingWorker.RunWorkerAsync(); in DoWork from another BackgroundWorker thread.
So when _FileCountingWorker reports progress it wont come back to the UI thread because it is not started from UI thread. That's why you are getting cross thread exception.
Try to call _FileCountingWorker.RunWorkerAsync() from UI thread or from _FileProcessingWorker_ProgressChanged event.
Otherwise you can use:
private void _FileCountingWorker_ProgressChanged(object sender, ProgressChangedEventArgs e)
{
if (!Dispatcher.CheckAccess()) // CheckAccess returns true if you're on the dispatcher thread
{
Dispatcher.Invoke(new Action<object, ProgressChangedEventArgs>(_FileCountingWorker_ProgressChanged), sender, e);
return;
}
if (typeof(object[]) == e.UserState.GetType())
{
object[] StatusMsg = (object[])e.UserState;
if (6 == StatusMsg.GetLength(0))
{
if (StatusMsg[5] != null)
{
lblCountingFiles.Text = StatusMsg[5].ToString();
}
}
}
}
I think the problem is on the main thread you have
object[] CurrentStatus;
in the background you could be newing it before reports progress gets to it
(or at the same time)
kill the above
just create the object in the do_work
object[] CurrentStatus = new object[6];

How to get selected value or index of a dropdownlist upon entering a page?

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

Prevent task being executed again while it is still running

Boys and Girls,
I got this method (task) that gets executed when I select a node in a treeview. It retreives data from a database and puts in a ReportControl (Codejock).
What I need is to prevent that this method (task) gets executed again while it is still running.
I've been experimenting with booleans set to false when starts and set to true if finishes but that doesn't work for some reason.......
here is the code:
the event where the method gets executed:
private void tvObjects_AfterSelect(object sender, TreeViewEventArgs e)
{
try
{
tvObjects.PreseveTreeState = true;
tvObjects.SaveTreeState();
tvObjects.SelectedNode.BackColor = Color.FromArgb(191, 210, 234);
AllowPreview = false;
WordPreviewer.UnloadPreviewHandler();
viewer1.Image = null;
rcDocumenten.ClearContent();
rcEmail.ClearContent();
var n = e.Node as ExtendedTreeNode;
tvObjects.CurrentNode = e.Node;
SelectedObjectNode = n;
WordPreviewer.FileName = null;
if (n != null)
{
Document.SetDossierNummer(n.DossierNr);
}
var selNode = e.Node as ExtendedTreeNode;
if (selNode != null && selNode.DossierNode)
{
if (selNode.IsFolder)
{
DossierNr = Convert.ToInt32(selNode.DossierNr);
SelectedObjectNode = selNode;
var col = new col();
col.CreateCurrentDossierDocumentsList(Convert.ToInt32(selNode.DossierNr.ToString()),
selNode.Tag.ToString());
col.CreateCurrentEmailList(selNode.DossierNr, Convert.ToInt32(selNode.Tag.ToString()));
var t =
new Thread(
() =>
rcDocumenten_Populate(Convert.ToInt32(selNode.DossierNr.ToString()),
selNode.Tag.ToString()));
t.Start();
var t2 = new Thread(
() => rcEmail_Populate(selNode.DossierNr, Convert.ToInt32(selNode.Tag.ToString())));
t2.Start();
tcDocumenten.SelectedTab = selNode.Text.Contains("Email") ? tpEmail : tpDocumenten;
}
else
{
tpDocumenten.Text = #"Documenten (0)";
tpEmail.Text = #"Emails (0)";
SelectedBestandId = -1;
SelectedBestandsNaam = string.Empty;
SelectedEmailId = -1;
SelectedEmailOnderwerp = string.Empty;
}
}
else if (selNode != null && selNode.PersonalNode)
{
if (!selNode.IsMedewerker)
{
var t =
new Thread(
() => rcDocumenten_PersoonlijkeMappenPopulate(Convert.ToInt32(selNode.Tag.ToString())));
t.Start();
}
}
}
catch (InvalidOperationException iex)
{
MessageBox.Show(iex.ToString());
}
catch (Exception ex)
{
var dmsEx = new DmsException("Fout tijdens het uitvoeren event AfterSelect tvObjects ", "VDocumenten (tvObjects Event: AfterSelect)", ex);
ExceptionLogger.LogError(dmsEx);
}
}
the method that should not run twice:
public void rcDocumenten_PersoonlijkeMappenPopulate(int personalFolderId)
{
try
{
AllowPreview = false;
var oc = new col();
rcDocumenten.FocusedRow = null;
oc.CreateCurrentPersoonlijkeDocumentsList(personalFolderId);
UpdateUI(false);
if (rcDocumenten.InvokeRequired)
{
rcDocumenten.Invoke((MethodInvoker)delegate
{
rcDocumenten.Records.DeleteAll();
rcDocumenten.Redraw();
_gegevensLaden = new GegevensLaden(this);
_gegevensLaden.Show();
//Documenten uit Database ophalen
_gegevensLaden.progressbar.Maximum = col.ListPersoonlijkeDocuments.Count;
foreach (var document in col.ListPersoonlijkeDocuments)
{
var versie = Convert.ToDecimal(document.Versie.ToString());
if (document.OriBestandId == 0)
{
//Record toevoegen
rcDocumenten_Persoonlijk_AddRecord(document.BestandId, document.BestandsNaam, versie,
document.DatumToevoeg, document.DatumUitcheck, document.UitgechecktDoor, document.Eigenaar,
document.DocumentType, document.DocumentProgres);
}
_gegevensLaden.progressbar.Value = _gegevensLaden.progressbar.Value + 1;
_gegevensLaden.progressbar.Update();
}
var aantalRecords = 0;
for (var i = 0; i < rcDocumenten.Records.Count; i++)
{
aantalRecords++;
for (var j = 0; j < rcDocumenten.Records[i].Childs.Count; j++)
{
aantalRecords++;
}
}
tpDocumenten.Text = #"Documenten (" + aantalRecords + #")";
rcDocumenten.Populate();
Invoke(new UpdateUIDelegate(UpdateUI), new object[] { true });
});
}
//"dd-MM-yyyy HH:mm:ss"
AllowPreview = true;
}
catch (Exception ex)
{
var dmsEx = new DmsException("Fout bij de populatie van Report Control", "VDocumenten (rcDocumenten_Persoonlijk_Populate)", ex);
ExceptionLogger.LogError(dmsEx);
}
}
You can check if the thread/task has completed. Change the thread creation to use a Task
_t =
Task.Factory.StartNew(
() =>
rcDocumenten_Populate(Convert.ToInt32(selNode.DossierNr.ToString()),
selNode.Tag.ToString()));
Then you can keep the Task around in the class scope. As you see above, I called it _t.
private Task _t; // documenten vullen achtergrond thread
Now, instead of blindly starting the Task, check if the Task should be started.
if (_t == null || _t.IsCompleted) {
That would solve your current issue.

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.

How to Fire an event for another Control while performing DataGridView_CellContentClick?

Actually, I have fired an event on DataGridView_CellContentClick which perform an operation relating to datagridview like changing cell's value But before performing this action i want to make changes(or fire) an another operation on another control i.e. ListView .But this is not gone happens although i place another operation before datagridview's operation. Anybody please help me out.
And my code goes like this:-
private void dGridDeviceList_CellContentClick(object sender, DataGridViewCellEventArgs e)
{
//DataGridViewCell dcell = dGridDeviceList.Rows[e.RowIndex].Cells[e.ColumnIndex];
if (e.RowIndex >= 0)
{
ListViewItem litem1 = lvInformation.Items.Add("101");
litem1.SubItems.Add(string.Empty);
litem1.SubItems[1].Text = "Connected.";
ListViewItem litem5= lvErrorList.Items.Add("check ");
Cursor = Cursors.WaitCursor;
List<cException> cxp = new List<cException>();
cDeviceModel cdm = new cDeviceModel();
ListViewItem litem = new ListViewItem();
DataGridViewRow drow = new DataGridViewRow();
cDeviceUtility cUtil = new cDeviceUtility();
List<cAction> catn = new List<cAction>();
drow = dGridDeviceList.Rows[e.RowIndex];
cdm = (cDeviceModel)drow.Tag;
if (e.ColumnIndex == 6)
{
if (dGridDeviceList.CurrentCell.Value.ToString() == "Connect")
{
litem1= lvInformation.Items.Add("101");
litem1.SubItems.Add(string.Empty);
litem1.SubItems[1].Text = "Connected.";
//lvInformation.Items.Insert(0, "101");
//lvInformation.Items[0].SubItems.Add("Connected");
}
// connect disconnect button column
if (cdm.IsConnected)
{
ListViewItem litem2 = lvInformation.Items.Add("102");
litem2.SubItems.Add(string.Empty);
litem2.SubItems[1].Text =string.Format("Disconnecting from {0} device.",dGridDeviceList.CurrentRow.Cells["colDeviceName"].Value);
// then disconnect the device
cdm.IsConnected = false;
cdm.DeviceInterface.Disconnect();
dGridDeviceList.Rows[e.RowIndex].Tag = cdm;
dGridDeviceList.Rows[e.RowIndex].Cells[6].Value = "Connect";
dGridDeviceList.Rows[e.RowIndex].Cells[1].Value = img16x16.Images["notconnected"];
dGridDeviceList.Rows[e.RowIndex].Cells[8].Value= 0;
dGridDeviceList.Rows[e.RowIndex].Cells[8].Tag = "Not Connected";
dGridDeviceList.Refresh();
litem2 = lvInformation.Items.Add("103");
litem2.SubItems.Add(string.Empty);
litem2.SubItems[1].Text = string.Format("Disconnected from {0} device.", dGridDeviceList.CurrentRow.Cells["colDeviceName"].Value);
}
else
{
// string test = lvInformation.Items[0].SubItems[1].ToString();
// catn.Add(new cAction { Number = lvInformation.Items.Count+1, Message = string.Format("Trying to connect with {0}", dGridDeviceList.Rows[e.RowIndex].Cells["colDeviceName"].Value) });
//// lvInformation.Items.Clear();
// foreach (cAction Actn in catn)
// {
// litem=lvInformation.Items.Insert(0, (lvInformation.Items.Count + 1).ToString());
// litem.SubItems.Add(catn[catn.Count -1].Message);
// }
// then connect the device
if (!ConnectToDevice(ref drow, out cxp) == true)
{
foreach (cException err in cxp)
{
litem = lvErrorList.Items.Insert(0, err.Number.ToString());
if (err.EType == ErrorType.Error)
{
litem.ImageKey = "error";
}
else if (err.EType == ErrorType.Warning)
{
litem.ImageKey = "warning";
}
else if (err.EType == ErrorType.Information)
{
litem.ImageKey = "information";
}
litem.SubItems.Add(err.Message);
litem.SubItems.Add(err.Source);
}
}
else
{
dGridDeviceList.Rows[e.RowIndex].Cells[0].Value = true;
dGridDeviceList.Rows[e.RowIndex].Tag = drow.Tag;
dGridDeviceList.Rows[e.RowIndex].Cells[6].Value = "Disconnect";
dGridDeviceList.Rows[e.RowIndex].Cells[1].Value = img16x16.Images["connected"];
dGridDeviceList.Rows[e.RowIndex].Cells[8].Value = 0;
dGridDeviceList.Rows[e.RowIndex].Cells[8].Tag = "Ready";
dGridDeviceList.Refresh();
RemoveSelectionRow();
}
}
}
else if (e.ColumnIndex == 7)
{
// view logs button column
pbarMain.Value = 100;
ViewLogs(dGridDeviceList.Rows[e.RowIndex],ref lvAttnLog ,ref lvErrorList);
}
Cursor = Cursors.Arrow;
}
}
considering this is winform
private void buttonCopyContent_Click(object sender, EventArgs e)
{
//do something
}
you can call this event via following line
this.Invoke(new EventHandler(buttonCopyContent_Click));

Categories