C# Delegate eventhandler SelectedIndexChanged

3.1k views Asked by At

I want to pass another value to the method LeCmb_Statut_SelectedIndexChanged, how can I proceed?

I have the code:

SqlDataReader reader = comm.ExecuteReader(); 
while (reader.Read())
{
   ...
   DropDownList LeCmb_Statut = new DropDownList();
   string tempLabel = reader["LIBELLE"].ToString();
   string templabelVeh = reader["LIBVEH"].ToString()
}

How can I pass these temp variables into LeCmb_Statut_SelectedIndexChanged?

LeCmb_Statut.SelectedIndexChanged += new EventHandler(LeCmb_Statut_SelectedIndexChanged);
2

There are 2 answers

0
pomarc On BEST ANSWER

You could use the Tag property of dropdownlist. first, create a simple DTO:

public class LabelDTO
{
   public string Label {get;set;}
   public string LabelVeh {get;set;}
} 

then:

while (reader.Read())
{
   ...
   DropDownList LeCmb_Statut = new DropDownList();
   LabelDTO lbl= new LabelDTO(){Label=reader["LIBELLE"].ToString(), LabelVeh=reader["LIBVEH"].ToString()};

    LeCmb_Statut.Tag=lbl;
}

then inside the LeCmb_Statut_SelectedIndexChanged:

LeCmb_Statut_SelectedIndexChanged (object sender, System.EventArgs e)
{
    LabelDTO labelDTO= ((DropDownList)sender).Tag as LabelDTO ;
    if (labelDTO!=null)
     {
        ///here you can use the label and labelVeh properties.

     }
}
0
Marc Gravell On

You can use an anonymous method to capture them:

string tempLabel = reader["LIBELLE"].ToString();
string templabelVeh = reader["LIBVEH"].ToString()
LeCmb_Statut.SelectedIndexChanged += delegate {
    // do something fun with   tempLabel  and templabelVeh 
};

this could be inline for small blocks, or for longer code - just pass to a method:

string tempLabel = reader["LIBELLE"].ToString();
string templabelVeh = reader["LIBVEH"].ToString()
LeCmb_Statut.SelectedIndexChanged += delegate {
    DoSomethingFun(tempLabel,templabelVeh);
};

or if you need the sender/args:

string tempLabel = reader["LIBELLE"].ToString();
string templabelVeh = reader["LIBVEH"].ToString()
LeCmb_Statut.SelectedIndexChanged += delegate(object sender, EventArgs args) {
    DoSomethingFun(sender,args,tempLabel,templabelVeh);
};

or in C# 3.0:

string tempLabel = reader["LIBELLE"].ToString();
string templabelVeh = reader["LIBVEH"].ToString()
LeCmb_Statut.SelectedIndexChanged += (sender, args) =>
    DoSomethingFun(sender,args,tempLabel,templabelVeh);