2015-05-11 56 views
1

在我的計劃中,單選按鈕匹配所選項目的多個位置都已經被檢查了,我有很多的if語句,像這樣:單選按鈕,如何更換所有這些if語句

DataRowView TempRow = (DataRowView)ScheduleDataGrid.SelectedItem; 

if (Convert.ToString(TempRow["Bio"]) == "Bio1") 
{ 
    BioRB1.IsChecked = true; 
} 
if (Convert.ToString(TempRow["Bio"]) == "Bio2") 
{ 
    BioRB2.IsChecked = true; 
} 
if (Convert.ToString(TempRow["Bio"]) == "Bio3") 

等...我想用短而聰明的東西來取代所有這些。 我嘗試使用生物的數量涉及到的按鈕,像這樣:

string bioselected = Convert.ToString(TempRow["Bio"]); 

int i = Convert.ToInt16(bioselected.Substring(bioselected.Length - 1, 1)); 

BioRB[i].IsChecked = true; 

,但做了BioRB [I]不起作用,它忽略了[i]和說BioRB不存在。還有其他建議嗎?

+0

噢,對不起,這是C# – humudu

+0

什麼UI框架? ASP?的WinForms? WPF? –

+0

,這是一個WPF應用 – humudu

回答

3

BioRB[i]沒有做你認爲它正在做的事情。所有變量引用(包含的控件)必須在編譯時明確定義 - 您不能通過構建與該名稱匹配的字符串來引用控件的名稱。**

嘗試創建單選按鈕的列表。然後你可以索引到列表中:

List<RadioButton> radioButtons = new List<RadioButton>() 
{ 
    BioRB1, 
    BioRB2 
}; 

string bioselected = Convert.ToString(TempRow["Bio"]); 
int i = Convert.ToInt16(bioselected.Substring(bioselected.Length - 1, 1)); 
radioButtons[i].IsChecked = true; 

**從技術上講,你可以通過反射來做到這一點,但它比你試過的要複雜得多。

+0

謝謝,這似乎工作:) – humudu

+0

@humudu不客氣,但在所以,「謝謝」帖子是不鼓勵的。如果您發現這有幫助,請考慮[接受](http://stackoverflow.com/help/someone-answers)的答案。 –

+0

@BJMyers這是我以爲他想要的,但我不確定...加上一個使用名單 waltmagic

0

這也許會更好看:

string caseSwitch = Convert.ToString(TempRow["Bio"]); 
switch (caseSwitch) 
{ 
    case "Bio1": 
     BioRB1.IsChecked = true; 
     break; 
    case "Bio2": 
     BioRB2.IsChecked = true; 
     break; 
    case "Bio3": 
     BioRB3.IsChecked = true; 
     break; 
    default: 
     Console.WriteLine("Default case...is optional"); 
     break; 
} 

另外,嘗試做什麼Alybaba726說和使用CellContentClick或者是這樣的:

private void dataGridView1_CellContentClick(object sender, DataGridViewCellEventArgs e) 
    { 
     DataGridView dgv = (DataGridView)sender; 
     if(e.ColumnIndex == dgv.Columns["Bio"].Index) 
     { 
      string bioSelected = dgv.Rows[e.RowIndex].Cells[e.ColumnIndex].Value.ToString(); 

      switch (bioSelected) 
      { 
       case "Bio1": 
        BioRB1.IsChecked = true; 
        break; 
       case "Bio2": 
        BioRB2.IsChecked = true; 
        break; 
       case "Bio3": 
        BioRB3.IsChecked = true; 
        break; 
       default: 
        Console.WriteLine("Default case...this is optional"); 
        break; 
      } 
     } 
    }