2011-02-09 221 views
1

我想將另一個值傳遞給方法LeCmb_Statut_SelectedIndexChanged,我該如何繼續?C#委託事件處理程序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

@ user609511:描述更多你有什麼和你想要達到什麼。 – abatishchev 2011-02-09 10:18:52

+0

當前您正在爲每個記錄創建一個新的DropDownList。將項目添加到預先存在的DropDownList是否更有意義? – 2011-02-09 10:21:54

回答

2

您可以使用dropdownlist的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. 

    } 
} 
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); 
相關問題