Quite new to generics, I have a lot of methods with al the same code only the used classobject is different.But I do not know how to make this generic (it gives me errors) :
private void btn_Click(object sender, EventArgs e)
{
ArrayList ar = new ArrayList();
ar.Add("");
this.txtUitleg.Lines = (string[])ar.ToArray(typeof(string));
typeDataSource = typeof(classname1);
typeItems = classname1.Items.GetType();
codeTabel = "classname1";
dataGridView2.DataSource = classname1.Items;
lblTitel.Text = codeTabel;
}
This is the code I have for about 10 different button_clicks events. Only the classname1 is different. So I think this is a good piece of code to use generics.
What I tried :
private void btn_Click(object sender, EventArgs e)
{
GenericsButton_Click();
}
private void GenericsButton_Click
{
ArrayList ar = new ArrayList();
ar.Add("");
this.txtUitleg.Lines = (string[])ar.ToArray(typeof(string));
typeDataSource = typeof(T);
typeItems = T.Items.GetType();
codeTabel = T.ToString();
dataGridView2.DataSource = T.Items;
lblTitel.Text = codeTabel;
}
But this is not correct. Is it possible to point me out ?
Thanks
Sam HobbsPosted Feb 13, 2010, 4:23 PM
As for identifying what button has been clicked (is that what you are asking?), in C++ it is common to derive a class from a control class, and the derived class can have additional data and methods. As far as I know, that is entirely possible using C# too; that is, derive a class from Button. Another possibility is to create a UserControl with a button in it. Another possibility is to use the Tag member of Button (it is a member of the Control class that controls derive from) to have instance-specific data.
haezebanPosted Feb 13, 2010, 5:36 AM
After a lot of reading. I don't think this method is a good thing to use generic's.
My UI has a lot of button's. All buttons has the same functionality (see example - they fill up a datagrid). The only difference is the used object collection (classname1 in example - I have theis code 50-times but once with classname1, then classname2 etc..... ).
I am looking now to do the following : on each button I will attach the same button_click event (so just 1 time the code), but in that event-code I need to know which collection I need to use.
Is there a way I can give with the event some information ex classname1, calssname2 ...?? Or do I need to test which button is pressed?
tkx
haezebanPosted Feb 13, 2010, 4:20 AM
Thanks for the answer.
I changed my code, but It gives me the error that T is type parameter, which is not valid in given context.
This on the lines T.Items.GetType() and T.GetType().Name
T will have always the same structure. It is not a standard type as string, Int, double .... It is a self-made class. But always with the same structure.
Tkx,
Sam HobbsPosted Feb 12, 2010, 1:49 PM
One thing that I see is that for codeTabel you probably need:
codeTabel = T.GetType().Name;