我想将另一个值传递给方法LeCmb_Statut_SelectedIndexChanged,我该如何处理?
我有代码:
SqlDataReader reader = comm.ExecuteReader();
while (reader.Read())
{
...
DropDownList LeCmb_Statut = new DropDownList();
string tempLabel = reader["LIBELLE"].ToString();
string templabelVeh = reader["LIBVEH"].ToString()
}
如何将这些临时变量传递给LeCmb_Statut_SelectedIndexChanged
?
LeCmb_Statut.SelectedIndexChanged += new EventHandler(LeCmb_Statut_SelectedIndexChanged);
答案 0 :(得分:2)
您可以使用下拉列表的Tag属性。 首先,创建一个简单的DTO:
public class LabelDTO
{
public string Label {get;set;}
public string LabelVeh {get;set;}
}
然后:
while (reader.Read())
{
...
DropDownList LeCmb_Statut = new DropDownList();
LabelDTO lbl= new LabelDTO(){Label=reader["LIBELLE"].ToString(), LabelVeh=reader["LIBVEH"].ToString()};
LeCmb_Statut.Tag=lbl;
}
然后在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.
}
}
答案 1 :(得分:2)
您可以使用匿名方法捕获它们:
string tempLabel = reader["LIBELLE"].ToString();
string templabelVeh = reader["LIBVEH"].ToString()
LeCmb_Statut.SelectedIndexChanged += delegate {
// do something fun with tempLabel and templabelVeh
};
这可以是小块的内联,也可以是更长的代码 - 只需传递给方法:
string tempLabel = reader["LIBELLE"].ToString();
string templabelVeh = reader["LIBVEH"].ToString()
LeCmb_Statut.SelectedIndexChanged += delegate {
DoSomethingFun(tempLabel,templabelVeh);
};
或者如果您需要发件人/ args:
string tempLabel = reader["LIBELLE"].ToString();
string templabelVeh = reader["LIBVEH"].ToString()
LeCmb_Statut.SelectedIndexChanged += delegate(object sender, EventArgs args) {
DoSomethingFun(sender,args,tempLabel,templabelVeh);
};
或在C#3.0中:
string tempLabel = reader["LIBELLE"].ToString();
string templabelVeh = reader["LIBVEH"].ToString()
LeCmb_Statut.SelectedIndexChanged += (sender, args) =>
DoSomethingFun(sender,args,tempLabel,templabelVeh);