Creating dynamic eventhandler: ddl.SelectedIndexChanged += new EventHandler(string); - c#

I promise that I did search this issue before posting. :) It may have also been answered but maybe in a different context which I could not properly understand. The closest one that I think sort-of matches my query is this: get-eventhandler-by-name. Again, I am new to this and I am just learning as I go so please bear with me.
Anyway, my query is I have several dynamically created controls with IDs taken from a database. Now I want to attach these controls to its related events (mostly DropDown_SelectedIndexChanged) by looping through my database and creating the events by passing a string. Hence:
ddl.SelectedIndexChanged += new EventHandler(string);
Earlier I was hardcoding it with ifs like so:
if (ddl.ID == "brandCode")
{
ddl.SelectedIndexChanged += new EventHandler(brandCode_SelectedIndexChanged);
}
which will obviously work but it's not really dynamic.
And lol I even tried:
ddl.SelectedIndexChanged += new EventHandler(dr["AspId"].ToString().Trim());
which is obviously wrong because it is passing a string instead of an object.
Disclaimer. This question is related to my earlier post Dynamically created cascading dropdown lists

Related

How to add completion words dynamically to VS2013 Syntax Extension (MEF)

It's very possible that I just don't understand the problem space, but I'm having trouble figuring out the MEF (Editor Classifier project).
I've created (piecing together the Walkthrough guides from MSDN https://msdn.microsoft.com/en-us/library/ee197665.aspx) a syntax highligher for Informix Stored Procedure language.
One major problem I have is - I want to be able to find all instances of the keyword "DEFINE" and populate the word directly following it into the Statement Completion extension I have (currently it's populated from a defined list of words).
Much like C#'s native support - when you define a variable, it becomes available in the autocompletion dropdown.
I got rid of the in class hardcoding (from the walkthrough) and my completion words are defined like this:
List<Completion> completions = new List<Completion>();
CompletionTags completionTags = new CompletionTags();
foreach (string completionTag in completionTags.completionTags)
{
completions.Add(new Completion(completionTag));
};
My CompletionTags class is pretty simple:
class CompletionTags
{
public List completionTags;
public CompletionTags()
{
this.completionTags = new List<string> {
// SQL keywords
"COUNT",
"FROM",
"HAVING",
};
}
I know WHAT I need to do. I somehow need to hijack the buffer when it changes and find all occurrences of 'DEFINE ([a-zA-Z0-9_]{1,})' and add \1 to the completionTags list.
I have no idea HOW to do this. Any pointers in the right (or any) direction at this point would be greatly appreciated.
Be kind - we've all been out of our depth at some stage (I've been programming in C# now for 3 days)...
Reading this answer will be helpful.
Look at:
XML Editor IntelliSense Features
Schema Cache

Cascading databound comboboxes

I'm new here this is my first question and I beforehand apologize for any lack of information, search or tags in the post or anything at all.
I'm writing a pretty simple winforms program, and I'm having problems with cascading combo boxes, pretty much like country>Estate>City I'm new to this, I'm using Entity Framework and I'm getting by with something like this:
private void Form_CadAnimal_Load(object sender, EventArgs e)
{
using (DbClinvetEntities ctx = new DbClinvetEntities())
{
cmb_especie.DataSource = ctx.Especie;
cmb_especie.DisplayMember = "Nome";
cmb_especie.ValueMember = "EspecieID"
cmb_raca.DataSource = ctx.raca;
cmb_raca.DisplayMember = "Nome";
cmb_raca.ValueMember = "RacaID";
}
}
So far so good all is going ok, I get them to be populated, I've found countless posts on the matter, but perhaps for lack of knowledge I could not relate them to my situation.
now all I would like to do is filter cmb_Raca by the value selected in cmb_Especie, just to make it clearer Raca table has a foreign key on Especie table, pretty much like you would expect country>estate to be.
I've found posts where a new context is generated on SelectedIndexChanged and a whole new binding is done, but I wonder if there is a way to make this work without making further calls to the Db, any way to take the list of objects and work them offline after the first access?
Sorry if this is anyhow unclear, I'll glady edit the post to provide further information if necessary.
try using the SelectedIndex as your query select command.you can build a module for talking to the database that takes the SelectedIndex.ToString() as a parameter to build your Query and fill data to your form based on that. the Combobox doesn't necessarily have to be databound when it is used that way.

Using Form to dynamically generate buttons/panels for a Rule Engine

I'm writing my own Rule Engine, I've looked at a couple that existed but I'm looking for something else which I couldn't find examples to.
I'm looking for a similar application where I can dig into and learn how to do it.
Now, my question is REGARDLESS of the Rule Engine, more of a Form/Dynamic question, but if with your answer you can
relate to what I eventually want to do, that would be great.
Regarding the UI, I'm using Visual Form and the I'd like it to be like this:
http://i.imgur.com/5istREF.jpg
Now, once the user select on the final check box "And/Or" I want him to be able to enter another rule, exactly the same format as the first one.
http://i.imgur.com/N588sjj.jpg
Now the user can basically do it as many times as he wants, so I'm looking for a way to dynamically handle it and create buttons/pannels or even using the same ones (but every time he can enter different values).
Like I've said if you know any similar application/code that I can look into, regardless of rule engine, that will help as well.
Eventually I will take all the fields that he entered and turn it into code.
If I understand you correctly, what you can do is make a controller of your own which is defined in an additional form and then you can add it to your main form as much as you want.
You can define this new controller (meaning a new form) to hold only a single line of the comboBox and then add it to a location in your main form which is based on the location of the previous controller.
Here is an example which adds several control of a class called CNewControl to a tab called newControlsTab one after the other.
int controlHeight = 0;
foreach (CNewControl newControl in newControlList)
{
this.newControlsTab.Controls.Add(newControl );
newControl.Dock = DockStyle.Top;
newControl.Location = new System.Drawing.Point(40, 3 + controlHeight);
controlHeight += newControl .Size.Height;
}
You can of course change it to add your line only once when the user chooses the appropriate option in which a line should be added.

URL Querystring - Find, replace, add, update values?

We inherited some C# code as part of a project from another company which does URL redirects that modifies the existing query string, changing values of items, adding new params, etc as needed. The issue however is that the code is buggy at best, and ends up duplicating items in the query string instead of updating them properly. The code works on the first pass but on additional calls the duplication issues become apparent.
Ex: MyPage.aspx?startdate=08/22/09&startdate=09/22/09
Instead of duplicating the item it needs to be either updated with the new value if it already exists, or added if not there already.
Is there a C# class or set of functions for handling query strings, allowing a simple means to access and update/add parameters that gets around these issues instead of the blind add approach that seems to be in use now with the code? This needs to be able to handle multiple parameters that may or may not exists at all times and be added and updated on subsequent calls.
We would sooner use existing logic than recreate something if possible so as to get this resolved quickly in a semi standard way for future maintainability and reuse.
Yes I would suggest converting the querystring to a collection by using HttpUtility.ParseQueryString()
You can then find/add/update/replace values directly in the collection, before re-creating the querystring from this collection.
This should make it easier to spot duplicates.
You can access and manipulate all values of your Querystring through the Request.QueryString collection. Here's a link.
this seems a basic design problem.
instead of updating the current query string, what SHOULD be done is simply adding all the parameters to the base at every time.
sure, you CAN update it, but (pseudocode)
if querystring exists
then update query string
else
add query string
will get crazy when you start using more than 1 variable.
redesign would be best, effort allowing.
The WCF REST Starter Kit available on ASP.NET also include a new "HttpQueryString" helper class that will most likely be included in the .NET 4.0 time frame into the base class library.
See an excellent screencast on how to use this utility class here:
http://channel9.msdn.com/shows/Endpoint/endpointtv-Screencast-HttpClient-Query-String-and-Form-Input-Management/
Marc

C# refreshing textbox from BindingSource

I am having difficulty refreshing windows forms controls that are using a BindingSource object. We have a CAB/MVP/SCSF client that I (actually “we” since it is a team effort) are developing that will interact with WCF services running on a remote server. (This is our first attempt at this, so we are in a learning mode). One of the calls (from the Presenter) to the service returns a DataSet that contains 3 DataTables, named “Contract”, “Loan” and “Terms”. Each table contains just one row. When the service returns the dataset, we store it in the SmartPart/View in a class member variable, by calling a function in the view called BindData() and passing the dataset in to the view from the presenter class;
private System.Data.DataSet _ds = null;
public void BindData(System.Data.DataSet ds)
{
string sErr = "";
try
{
_ds = ds; // save to private member variable
// more code goes down here
}
}
We are trying to bind each of the three DataTables to an assortment of Windows Forms TextBoxes, MaskedEditBoxes, and Infragistics UltraComboEditor Dropdown comboboxes We created three BindingSource objects, one for each DataTable using the VS2008 IDE.
private System.Windows.Forms.BindingSource bindsrcContract;
private System.Windows.Forms.BindingSource bindsrcLoan;
private System.Windows.Forms.BindingSource bindsrcTerms;
We are binding the values like this
if (bindsrcContract.DataSource == null)
{
bindsrcContract.DataSource = _ds;
bindsrcContract.DataMember = “contract”;
txtContract.DataBindings.Add(new Binding("Text", bindsrcContract, "contract_id", true));
txtLateFeeAmt.DataBindings.Add(new Binding("Text", bindsrcContract, "fee_code", true));
txtPrePayPenalty.DataBindings.Add(new Binding("Text", bindsrcContract, "prepay_penalty", true));
txtLateFeeDays.DataBindings.Add(new Binding("Text", bindsrcContract, "late_days", true));
}
if (bindsrcLoan.DataSource == null)
{
bindsrcLoan.DataSource = _ds;
bindsrcLoan.DataMember = “loan”;
mskRecvDate.DataBindings.Add(new Binding("Text", bindsrcLoan, "receive_date", true));
cmboDocsRcvd.DataBindings.Add(new Binding("Value", bindsrcLoan, "docs", true));
}
This works when we do the first read from the service and get a dataset back. The information is displayed on the form's controls, we can update it using the form, and then “save” it by passing the changed values back to the WCF service.
Here is our problem. If we select a different loan key and make the same call to the service and get a new DataSet, again with 3 tables with one row each, the controls (textboxes, masked edit boxes, etc.) are not being updated with the new information. Note that the smartPart/View is not closed or anything, but remains loaded in between calls to the service. On the second call we are not rebinding the calls, but simply trying to get the data to refresh from the updated DataSet.
We have tried everything we can think of, but clearly we are missing something. This is our first attempt at using the BindingSource control. We have tried
bindsrcContract.ResetBindings(false);
and
bindsrcContract.ResetBindings(true);
and
bindsrcContract.RaiseListChangedEvents = true;
and
for (int i = 0; i < bindsrcContract.Count; i++)
{
bindsrcContract.ResetItem(i);
}
As well as resetting the DataMember property again.
bindsrcContract.DataMember = ”Contract”;
We’ve looked at a lot of examples. Many examples make reference to the BindingNavigator but since the DataTables only have one row, we did not think we needed that. There are a lot of examples for grids, but we’re not using one here. Can anyone please point out where we are going wrong, or point us to resources that will provide some more information?
We’re using VisualStudio 2008, C# and .Net 2.0, XP client, W2K3 server.
Thanks in advance
wes
I was having a similar issue today and found this works.
private void btnCancel_Click(object sender, EventArgs e)
{
this.MyTable.RejectChanges();
this.txtMyBoundTextBox.DataBindings[0].ReadValue();
this.EditState = EditStates.NotEditting;
}
The underlying problem in both your questions is that the Binding-Manager keeps the links to the original objects.
When you assign _ds as the DataSource, the Binding-Manager analyzes the DataSet and acts accordingly. If you assign some other DataSet to _ds, the Binding-Manager has no way of knowing this. It still has the reference on the original DataSet-object. So this explains why you have to reset the DataSource-property to the new DataSet.
It also explains why the removing and adding of the table doesn't lead to your expected result. Again, the Binding-Manager holds the reference to the old table (or the first row in that table). The new table is never bound. Also in this case the reassigning of _ds does not help, because _ds points to the same DataSet-object as before. The Binding-Manager is smart enough to notice that it's the same object and does no rebinding action.
You either have to modify the contents of your bound objects (which fires a PropertyChanged-Event to which the Binding-Manager subscribes) or you have to trigger a complete rebind by assigning a different object to the DataSource-property.
This is a simplified description of what actually happens, but I hope it's enough to explain and solve your problem. Unfortunately I have yet to find a comprehensive explanation of WinForms databinding on the web (or elsewhere).
Failing all else, you can reassign the DataSource every time you receive a new dataset, doing something like this:
bindsrcContract.DataSource = typeof(System.Data.DataSet);
bindsrcContract.DataSource = _ds;
(Also, initializing DataMember first and then DataSource will give you better performance.)
Wes, I'm very glad I could help. I still remember an issue very similar to yours taking me weeks to figure out in the wild...
Regarding your questions, here's all I know:
If you set the DataSource first, then the DataMember, your data source will be scanned twice, since setting the DataMember subsequently changes the existing (valid) binding. If you do it the other way around, setting DataMember first (with DataSource being null or better, typeof(YourData)), binding only takes place once when you set the DataSource.
I think you can apply the same solution here. Instead of just
bindsrcContract.DataSource = _ds;
in your last line, you should write
bindsrcContract.DataSource = typeof(System.Data.DataSet);
bindsrcContract.DataSource = _ds;
Sorry to disappoint, but I learned all I know about data binding from MSDN as well as trial-and-error. It was quite painful. Hopefully someone else can chime in with a useful link or two.
try combination :
bindingsource.EndEdit() // writting data to underlying source
bindingSource.ResetBindings(false) // force controls to reread data from bindingSource
use this whenever you write something to controls.

Categories

Resources