2013-08-07 27 views
2

對於我的winforms程序,我有一個選項對話框,當它關閉時,我循環顯示所有對話框控件名稱(文本框,複選框等)及其對象值並將它們存儲在數據庫中,以便我可以在程序中讀取它。如下所示,我可以輕鬆地訪問Control組中的Text屬性,但沒有屬性可以訪問文本框的Checked值。在那種情況下,我需要先將c轉換爲複選框嗎?以編程方式通過winform控件獲取checkbox.checked值從循環到winform控件

conn.Open(); 
foreach (Control c in grp_InvOther.Controls) 
{ 
    string query = "INSERT INTO tbl_AppOptions (CONTROLNAME, VALUE) VALUES (@control, @value)"; 
    command = new SQLiteCommand(query, conn); 
    command.Parameters.Add(new SQLiteParameter("control",c.Name.ToString())); 
    string controlVal = ""; 
    if (c.GetType() == typeof(TextBox)) 
     controlVal = c.Text; 
    else if (c.GetType() == typeof(CheckBox)) 
     controlVal = c.Checked; ***no such property exists!!*** 

    command.Parameters.Add(new SQLiteParameter("value", controlVal)); 
    command.ExecuteNonQuery(); 
} 
conn.Close(); 

如果我需要先轉換c,我該怎麼做呢?

+0

是的,你必須轉換。 –

回答

1

是的,你需要將其轉換:

else if (c.GetType() == typeof(CheckBox)) 
    controlVal = ((CheckBox)c).Checked.ToString(); 

而且可以使檢查更易於閱讀:

else if (c is CheckBox) 
    controlVal = ((CheckBox)c).Checked.ToString(); 
+0

不錯的答案,並感謝關於縮短我的代碼的提示。 :) – gnarlybracket

-1

您可以在地方投:

controlVal = (CheckBox)c.Checked; 

BTW:controlVal並不需要是一個字符串,一個布爾值會做的工作,節省內存。

+0

這是行不通的。你仍然試圖轉換屬性('檢查')而不是控制('c')。 –

+0

實際上,'controlVal'確實需要是一個字符串,因爲我也存儲了Textboxes的Text屬性。 – gnarlybracket

+0

@Mario:錯了。 'c'是一個控制對象。您可以將其正確投射到CheckBox對象,然後直接訪問其屬性。 – Robert

-1

試試這個:

controlVal = Convert.ToString(c.Checked); 
+0

這不行,你必須先施放。 – Robert

0

羅伯特的回答是不錯的但讓我給你一個更好的

TextBox currTB = c as TextBox; 
if (currTB != null) 
    controlVal = c.Text; 
else 
{ 
    CheckBox currCB = c as CheckBox; 
    if (currCB != null) 
    controlVal = currCB.Checked; 
}